迁移
您需要为表创建迁移
您需要为关联的中间表创建迁移+关联创建的中间表名称是:categories_questions 或:questions_categories,在第二种情况下,您必须在模型中定义名称,如链接中所示
我需要手动为 HABTM 连接表创建迁移?
class CreateCategoriesQuestions < ActiveRecord::Migration
def self.up
create_table :categories_questions, :id => false do |t|
t.references :category
t.references :question
end
add_index :categories_questions, [:category_id, :question_id]
add_index :categories_questions, [:question_id, :category_id]
end
def self.down
drop_table :categories_questions
end
end
问题模型
class Question < ActiveRecord::Base
has_and_belongs_to_many :categories
end
类别模型
class Category < ActiveRecord::Base
has_and_belongs_to_many :questions
end
控制器材料
questions_controller.rb
def new
@question = Question.new
@question.categories.build #Build a categories_questions so as to use fields_for
end
表格资料
= f.fields_for :categories do |categories_fields|
= categories_fields.text_field :name
= categories_fields.text_field :description
在这一点上,我必须告诉你(我是 ruby 和 rails 的新手),要在这里创建一个新对象,你可以使用 jquery 正确附加一个 html 块名称,或者创建帮助程序(最后使用 javascript)添加一个新的对象并在保存时保存关联。在下一个链接中,有人演示了确切的方法。
http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for#512-Setting-child-index-while-using-nested-attributes-mass-assignment