我很难理解如何做到这一点。我有两个模型、一个项目和一个课程。
#project.rb
belongs_to :course
attr_accessible :course_id, :course
accepts_nested_attributes_for :course, reject_if: lambda { |a| a[:course_id] == 0 }
#course.rb
has_many :projects
在Projects#new
页面(子对象)上,我想输入一个新的名称course
并让它创建父对象。
这是我在视图中的尝试,但它似乎无法正常工作。
= form_for [@user, @project] do |f|
# Other fields
= fields_for :course do |builder|
= builder.label :name, 'Course Name'
= builder.text_field :name
= f.submit
稍后我将使用这个父对象来创建更多项目,但现在,让我们假设它不存在。
更新 1 我已将我的 fields_for 修改为(根据 Ryan 的要求):
= form_for [@user, @project] do |f|
# Other fields
= f.fields_for :course do |builder|
= builder.label :name, 'Course Name'
= builder.text_field :name
= f.submit
我正在使用haml,所以=
应该显示,但字段甚至没有显示在页面上或生成的html中。关于为什么会这样的任何线索?(提交按钮确实显示)
更新 2 我找到了一个潜在的解决方案,但我不确定这是否是解决这个问题的正确方法。在控制器中,我需要为 fields_for 显示建立一个课程。
# ProjectsController
def new
@project = @user.projects.new
@project.build_course
end
# project.rb
attr_accessible :course_attributes
# So yes, I now see what you were talking about, regarding the course_attributes