【问题标题】:How to create nested objects in Rails3 using accepts_nested_attributes_for?如何使用 Accept_nested_attributes_for 在 Rails3 中创建嵌套对象?
【发布时间】:2011-07-17 01:33:56
【问题描述】:

我不知道如何设置一个表单来创建一个新的Study,同时创建相关的StudySubjectFacility。如您在数据库关系模型中所见,user_idfacility_idstudy_subject_id 必须可用于创建 Study 对象。

这是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 完全陌生。抱歉问了一个愚蠢的问题。

【问题讨论】:

  • 图表是用什么软件画的?
  • @gmile 我用过cacoo.com

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


【解决方案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 %>

我希望这可以为您节省一些时间。我花了很多时间来了解必须如何设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2020-04-02
    • 1970-01-01
    • 2010-10-25
    • 2015-10-18
    • 2016-02-04
    相关资源
    最近更新 更多