5

関連するフォームとを作成しStudyながら、新しいフォームを作成する方法を理解できません。、、およびは、データベースリレーションモデルで確認できるように、オブジェクトを作成するために使用可能である必要があります。StudySubjectFacilityuser_idfacility_idstudy_subject_idStudy

データベースモデル

の移行は次のとおりですstudies。他のテーブルには外部キーが含まれていません。

def self.up
 create_table :studies do |t|
  t.references :user
  t.references :facility
  t.references :subject
  t.date "from"
  t.date "till"
  t.timestamps
 end
 add_index :studies, ["user_id", "facility_id", "subject_id"], :unique => true
end

モデルは、次の関連付けを定義します。

# user.rb
has_many :studies

# subject.rb
has_many :studies

# facility.rb
has_many :studies

# study
belongs_to :user
belongs_to :subject
belongs_to :facility

質問

1)has_manyとのbelongs_to定義は正しいですか?
2)accepts_nested_attributes_forstudyを使用して作成するにはどうすればよいですか? 3)スタディは1人のユーザーのみに属する必要があります。アソシエーションを保存するために、を他のすべてのオブジェクトに追加する必要がありますか?
user_id

2週間の広範な学習以来、私はRailsにまったく慣れていません。多分愚かな質問でごめんなさい。

4

1 に答える 1

4

うん。できます。仲の良い友人が助けを申し出ました。これが私たちが設定したものです。その間、名前を
に変更StudySubjectしたことを覚えておいてください。Subject

モデル study.rb

belongs_to :student, :class_name => "User", :foreign_key => "user_id"  
belongs_to :subject  
belongs_to :university, :class_name => "Facility", :foreign_key => "facility_id"  

accepts_nested_attributes_for :subject, :university

コントローラー studies_controller.rb

def new
  @study = Study.new
  @study.subject = Subject.new
  @study.university = Facility.new
end

def create
  @study = Study.new(params[:study])
  @study.student = current_user

  if @study.save
    flash[:notice] = "Successfully created study."
    redirect_to(:action => 'index')
  else
    render('new')
  end
end

認証にはdevise 、承認にはcancanを使用しています。そのためcurrent_user、コントローラーで を使用できます。

新しいスタディ ビュー new.html.erb

<%= form_for @study, :url => { :action => "create" } do |f| %>

  <table summary="Study form fields">

    <%= render :partial => "shared/study_form_fields", :locals =>  { :f => f } %>

    <%= f.fields_for :subject do |builder| %>
      <%= render :partial => "shared/subject_form_fields", :locals =>  { :f => builder } %>
    <% end %>

    <%= f.fields_for :university do |builder| %>
      <%= render :partial => "shared/facility_form_fields", :locals =>  { :f => builder } %>
    <% end %>

  </table>

  <p><%= f.submit "Submit" %></p>

<% end %>

これで時間を節約できることを願っています。物事をどのようにセットアップする必要があるかを理解するのに多くの時間を費やしました。

于 2011-03-17T14:37:33.470 に答える