[英]Rails 4 Create record with record.id of join table
Ruby on Rails 4
我正在嘗試讓表單在“測試”表中創建記錄。 記錄需要具有其聯接表中的ID(稱為問題_測試)。 我是否需要從表單中在questions_tests中創建記錄,然后創建測試記錄? 你會怎么做?
模型(不確定我是否正確命名聯接表):
class Test < ActiveRecord::Base
has_many :questions_tests
has_many :questions, :through => :questions_tests
end
class Question < ActiveRecord::Base
has_many :questions_tests
has_many :tests, :through => :questions_tests
end
class QuestionTest < ActiveRecord::Base
belongs_to :question
belongs_to :test
end
我的架構:
create_table "questions", force: true do |t|
t.string "content"
t.string "question_type"
t.string "category"
t.integer "product_id"
t.boolean "active"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
end
add_index "questions", ["product_id", "created_at"], name: "index_questions_on_product_id_and_created_at", using: :btree
create_table "questions_tests", id: false, force: true do |t|
t.integer "test_id", null: false
t.integer "question_id", null: false
end
create_table "tests", force: true do |t|
t.string "name"
t.integer "user_id"
t.string "type"
t.string "category"
t.string "description"
end
該表格應填寫“測試”屬性,並以某種方式具有questions_tests的ID。 現在, 我不知道如何發送或創建questions_tests記錄。
我的表單,不確定如何選擇問題並將其存儲到測試記錄中。 在這里,:question_id是未定義的,但是我需要在測試中存儲2到200個。
<h1>New Test</h1>
<%= form_for @test do |f| %>
<%= f.label :name, "Test Name" %><br>
<%= f.text_field :name, class: "input-lg" %>
<%= f.label :description, "Description" %><br>
<%= f.text_field :description, class: "input-lg" %>
<%= f.label :question_id %><br>
<%= f.select :question_id, Question.all.collect { |p| [ p.content, p.id ] }, class: "input-lg" %>
<%= f.label :category %><br>
<%= f.select :category, [ ["IP Voice Telephony", "ip_voice"], ["IP Video Surveillance", "ip_video_surveillance"], ["IP Video Telephony", "ip_video_telephony"], ["Enterprise Gateways", "enterprise_gateways"], ["Consumer ATAs", "consumer_atas"], ["IP PBX", "ip_pbx"] ], {prompt: "Select Category"}, class: "input-lg" %>
<%= f.label :type %><br>
<%= f.select :type, [ ["Beginner", "beginner"], ["Intermediate", "intermediate"], ["Advanced", "advanced"] ], {prompt: "Select Type"}, class: "input-lg" %>
<br/><br/><br/>
<%= f.submit "Create Test", class: "btn btn-lg btn-primary" %>
<% end %>
您需要研究fields_for
。
您的表單中將包含一個fields_for
塊
f.fields_for :questions do |question|
question.select(...)
end`
在此模塊中,您將有一種方法來選擇要添加到測試中的問題。 有一個名為cocoon的寶石,可以幫助您添加“添加問題”鏈接以添加更多問題。
您必須在測試模型中添加accepts_nested_attributes_for :questions
。 然后,Rails將自己創建QuestionTest
,您不必為此擔心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.