【发布时间】:2014-02-02 20:23:25
【问题描述】:
这是我的模型:
class Project < ActiveRecord::Base
has_many :project_applications
has_many :questions
accepts_nested_attributes_for :questions, :allow_destroy => true, :reject_if => proc { |a| a[:content].blank? }
end
class Question < ActiveRecord::Base
belongs_to :project
has_many :answers
has_many :project_applications, through: :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :project_application
end
class ProjectApplication < ActiveRecord::Base
belongs_to :project
belongs_to :student
has_many :answers
has_many :questions, through: :answers
end
项目由雇主创建,学生可以创建 project_application。 project_application 应该提出问题,然后显示与问题答案相对应的表单字段。我一生都无法弄清楚表单视图的外观。我需要一个 form_for ProjectApplication 接受嵌套属性作为答案。我的控制器中有以下内容:
class ProjectApplicationsController < ApplicationController
def new
@project = Project.find(params[:project_id])
@project_application = ProjectApplication.new
@project_application.project = @project
@project_application.project.questions.each do |question|
@answer = question.answers.build
@answer.project_application = @project_application #this line does not work
puts 'answer' + @answer.inspect.to_s
end
puts 'here are the answers' + @project_application.answers.inspect.to_s
end
end
问题在于答案没有正确地与 project_applications 相关联,因为 project_applications 还没有 id(因为它们尚未创建),因此无法进行关联,因此答案字段不是显示。这是我现在拥有的视图代码(不起作用):
<%= form_for @project_application, url: project_project_applications_path(@project.id), method: :post, remote: true do |f| %>
<%= f.fields_for :project do |proj| %>
<%= proj.fields_for :questions do |quest| %>
<%= quest.fields_for :answers do |answer| %>
<%= answer.text_area :content %>
<% end %>
<% end %>
<% end %>
<%= f.submit "APPLY" %>
<% end %>
如何更改视图和/或控制器以正确显示与问题和项目应用程序正确关联的答案字段?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 rails-activerecord nested-attributes has-many-through