我有用户在注册时需要回答一些问题。用户通过Answers连接表有很多问题。我只想弄清楚如何在Users#new action上创建表单。我正在使用simple_form。这是我的DB Schema:
ActiveRecord::Schema.define(:version => 20120831144008) do
create_table "answers", :force => true do |t|
t.integer "user_id"
t.integer "question_id"
t.text "response"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "answers", ["user_id", "question_id"], :name => "index_answers_on_user_id_and_question_id"
create_table "questions", :force => true do |t|
t.string "title"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "first_name"
t.string "last_name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
所以在用户#new页面上,我循环遍历问题标题,需要在每个问题下面创建一个文本区域并让它被创建。这是我到目前为止的表格,它不起作用,可能不会对解决方案有多大帮助,但是。
<%= simple_form_for(@user) do |f| %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :email %>
<%= f.input :phone %>
<%= f.input :organization %>
<%= f.input :primary_contact %>
<%= f.association :answers, collection: @questions %>
<% @questions.each do |question| %>
<div>
<strong><%= question.title %></strong>
<%= text_field_tag 'questions[]' %>
</div>
<% end %>
<%= f.button :submit %>
<% end %>
解决方案
我能够让它发挥作用,不确定这是否是绝对正确的方法,但它并不完全是丑陋的。在我的控制器中,我有@user.answers.build
,在我的simple_form中循环搜索问题,并创建一个填写了所需数据的答案字段。
<% Question.all.each do |question| %>
<%= f.simple_fields_for :answers do |a| %>
<div>
<strong>
<%= question.title %>
</strong>
<%= a.hidden_field :question_id, value: question.id %>
<%= a.input :response, label: false %>
</div>
<% end %>
<% end %>
答案 0 :(得分:0)
我相信你需要这样做:
<%= simple_fields_for @questions.each do |question| %>
确保您获得嵌套表单字段。