2014-04-28 44 views
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 %> 

回答

0

您需要查看fields_for

你會在你的形式

f.fields_for :questions do |question| 
    question.select(...) 
end` 

在這個區塊有fields_for塊,你有辦法選擇問題添加到測試。 有一個名爲cocoon的寶石,可以幫助你添加一個「添加問題」鏈接來添加更多問題。

您必須在您的測試模型中添加accepts_nested_attributes_for :questions。然後Rails將自己創建QuestionTest,你不需要擔心這一點。

+0

所以我不應該在我的數據庫中創建一個questions_tests表? – DDDD

+0

不,你需要一個。 Rails隱藏了創建這些連接表記錄的「複雜性」,但它並不改變它們需要存在的事實。 – Robin

+0

你可以避免的是有一個'QuestionTest'模型,並使用'has_and_belongs_to_many'。但我個人更喜歡按照你的方式去做。 – Robin

相關問題