如何使用accepts_nested_attributes_for在Rails3中创建嵌套对象?

时间:2011-03-17 01:11:09

标签: ruby-on-rails-3 associations nested-forms database-relations

我无法弄清楚如何设置一个可以创建新Study的表单,同时还可以创建相关的StudySubjectFacility。正如您在数据库关系模型中所看到的,user_idfacility_idstudy_subject_id必须可用于创建Study对象。

Database model

以下是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_manybelongs_to定义是否正确?
2)如何使用accepts_nested_attributes_for创建study? 3)研究应该只属于一个用户。我是否需要将user_id添加到每个其他对象中以存储关联?

自从2周的广泛学习以来,我对Rails全新。对不起,也许是一个愚蠢的问题。

1 个答案:

答案 0 :(得分: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 %>

我希望这会为你节省一些时间。我花了很多时间才意识到必须如何设置。