繁体   English   中英

Rails 4使用连接表的record.id创建记录

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM