0
Ruby on Rails 4Rails 4使用record.id創建連接表的記錄
我試圖讓表單在我的測試表中創建一條記錄。該記錄需要從其連接表中的id(s)稱爲questions_tests。我是否需要在表單的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
形式的測試應填寫屬性,並以某種方式有ID(S )來自questions_tests。現在我不知道如何發送或創建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 %>
所以我不應該在我的數據庫中創建一個questions_tests表? – DDDD
不,你需要一個。 Rails隱藏了創建這些連接表記錄的「複雜性」,但它並不改變它們需要存在的事實。 – Robin
你可以避免的是有一個'QuestionTest'模型,並使用'has_and_belongs_to_many'。但我個人更喜歡按照你的方式去做。 – Robin