我有一个像这样的强大参数
params.require(:survey).permit(option_booleans_attributes:[:id,:survey_id,:topic,:answer])
如果我使用rails f.input我得到了像
这样的参数“option_booleans_attributes”=> {“0”=> {“answer”=>“true”,“id”=>“5”},“1”=> {“answer”=> ;“false”,“id”=>“6”},“2”=> {“answer”=>“true”,“id”=>“7”}}}
但我需要显示option_booleans主题并让用户填写答案
<% @survey.option_booleans.each do |question| %> <%= question.topic %><br> <%= radio_button "option_booleans_attributes[]", "answer[#{question.id}]", "true" %>是 <%= radio_button "option_booleans_attributes[]", "answer[#{question.id}]", "false" %>否<br> <% end %>
但我不知道如何在参数中生成0 1 2 ..
关于我的survey.rb
class Survey < ActiveRecord::Base
has_many :option_booleans
accepts_nested_attributes_for :option_booleans
belongs_to :member
end
类OptionBoolean&lt;的ActiveRecord :: Base的
belongs_to:survey03
和OptionBoolean有主题:string和answer:boolean
我想让用户看到主题并更新答案
答案 0 :(得分:0)
您似乎错过了表单的几个部分:
#app/controllers/surveys_controller.rb
def new
@survey = Survey.new
@survey.option_booleans.build #-> creates ActiveRecord Object for your form
end
#app/views/surveys/new.html.erb
<%= form_for @survey do |f| %>
<%= f.fields_for :option_booleans do |option| %>
<% @survey.question_booleans.each do |question| %>
<%= question.topic %>
<%= f.radio_button "answer[#{question.id}]", "true" %>
<%= f.radio_button "answer[#{question.id}]", "false" %>
<% end %>
<% end %>
<% end %>
虽然我不太了解你的系统如何运作
您的调查包含许多选项,但您每次都会传递新属性以创建新选项。当然,您将option_booleans
作为加入模型,options
作为独立模型,并且:
#app/models/survery.rb
Class Survey < ActiveRecord::Base
has_many :option_booleans
has_many :options, through: :option_booleans
end
答案 1 :(得分:0)
尝试选择以下选项:
@variable_with_booleans = [true, false]
<%= f.select :param, @variable_with_booleans %>
回答你的最新评论: 我不确定,但尝试编辑您的表单
<%= form_for @question do |f| %>
<%= f.label :topic %>
<% @variable_with_booleans = [true, false] %>
<%= f.select :answer, @variable_with_booleans %>
<%= f.submit %>
<% end %>
并在控制器中编辑您的强参数,其中包含此操作
答案 2 :(得分:0)
我现在使用的是什么
<li><% @survey03.option_booleans.each do |question| %> <%= question.topic %><br> <%= radio_button "option_booleans_attributes[#{question.id}]", "answer", "true", :required => true %> <%= radio_button "option_booleans_attributes[#{question.id}]", "answer", "false", :required => true %> <% end %></li>
并在控制器中
params[:option_booleans_attributes].each do |option_id, attributes|
if option = OptionBoolean.find_by_id(option_id)
option.update_attributes(attributes)
end
end
我知道如果我想生成索引只需使用
<% @survey.option_booleans.each_with_index do |question, index| %> <%= question.topic %><br> <%= radio_button "option_booleans_attributes[#{index}]", "answer[#{question.id}]", "true" %> <%= radio_button "option_booleans_attributes[#{index}]", "answer[#{question.id}]", "false" %> <% end %>