How to create nested objects in Rails3 using accepts_nested_attributes_for?

I cannot figure out how to set up a form that will create a new one Study, as well as creating related StudySubjectand Facility. user_id, facility_idand study_subject_idshould be available for creating the object Study, as you can see in the model database relationships.

Database model

Here is the migration for studies. Other tables do not contain foreign keys.

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

Models define the following associations.

# 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

Questions

1) has_many belongs_to?
2) Study accepts_nested_attributes_for?
3) . user_id ?

Rails 2- . .

+5
1

. . . , .
, 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 %>

, . , , .

+4

All Articles