0
我有註冊時需要回答一些問題的用戶。用戶通過Answers連接表has_many問題。我只是想弄清楚如何在用戶#新動作上創建表單。我正在使用simple_form。這裏是我的DB模式:Ruby on Rails表格與has_many關係
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
所以對用戶#新的一頁,我通過這個問題稱號循環,並需要創建下面每個問題的文本區域,並將它獲取創建。這是我迄今爲止的一種形式,它不起作用,可能對解決方案不會有太大的幫助,但是。
<%= 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 %>
嘿,沒有真正能夠遵循這個邏輯太好。我用一個工作解決方案更新了我的問題,但可能不是最漂亮的。感謝回覆! – Lsdafjklsd