Ruby on Rails 4
我正在尝试让表单在我的Test表中创建一个记录。记录需要从其连接表中获取名为questions_tests的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
表单应该填写Test属性,并以某种方式从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 %>
答案 0 :(得分:0)
您需要查看fields_for
。
您的表单中有fields_for
块
f.fields_for :questions do |question|
question.select(...)
end`
在此块中,您可以选择要添加到测试中的问题。 有一个名为cocoon的宝石会帮助你添加一个&#34;添加问题&#34;链接以添加更多问题。
您必须在测试模型中添加accepts_nested_attributes_for :questions
。然后Rails会创建QuestionTest
本身,你不必担心这个。