我的模型关系设置如下:
# User model
class User < ActiveRecord::Base
belongs_to :company
has_many :answers
# groups
has_many :group_memberships
has_many :group_questions, through: :groups, source: :questions
has_many :groups, through: :group_memberships
# question
has_many :question_participants, as: :questionable
has_many :questions, through: :question_participants
# questions created by admin
class Question < ActiveRecord::Base
belongs_to :company
has_many :question_participants
has_many :answers
has_many :users, through: :question_participants,
source: :questionable, source_type: 'User'
has_many :groups, through: :question_participants,
source: :questionable, source_type: 'Group'
has_many :companies, through: :question_participants,
source: :questionable, source_type: 'Company'
end
# user answers to questions
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
end
现在我的答案存储了user_id,回复(他们的回答)和问题ID。 我现在想要创建的是一个表单,允许用户回答向他们提出的所有问题,并提交答案。
我在视图文件上设置了这样的表单(回答#new):
<%= form_for @answer do |f| %>
<% current_user.all_questions.each do |question| %>
<%= f.hidden_field :question_id, value: question.id %>
<p><%= question.name %>
<%= f.text_field :reply %>
<% end %>
<% end %>
哪个不起作用,我明白了 - 问题是我不知道如何让它与多次保存一起工作。
答案 0 :(得分:0)
我希望我能解决你的问题。以下是我的建议:
<%= form_for @answer do |f| %>
<% current_user.all_questions.each do |question| %>
<%= hidden_field_tag 'questions[][id]', question.id %>
<p><%= question.name %>
<%= text_field_tag 'questions[][reply]' %>
<% end %>
<% end %>
现在,在控制器操作中,您可以访问params[:questions]
,并且您可以像这样得到:[{"id"=>"1", "reply"=>"some text 1"}, {"id"=>"2", "reply"=>"some text 2"}]
:
# your_controller.rb
def create_answers
answers = params[:questions].map do |question|
current_user.answers.create(question_id: question[:id], reply: question[:reply])
end
if answers.any(&:invalid?)
flash[:error] = 'Some answers were not accepted'
redirect_to :back
else
redirect_to home_path
end
end