これを行う方法を理解するのに苦労しています。プロジェクトとコースの 2 つのモデルがあります。
#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