为HABTM选择许多框

我有两个型号; 在它们之间具有HABTM关联的问题和类别。 现在我想要一个表单,我可以编辑问题类别,但我不知道如何。 我从这开始,但我迷路了,我不确定如何命名“名称”属性等以及如何自动编辑/创建问题,我该如何设置?

  true, :size => 9} %>  

我设法设置问题(has_many) – >用fields_for和accepts_nested_attributes_for回答,但不是这个。

您应该看一下Ryan Bates 嵌套模型表单第1部分和嵌套模型表单第2 部分的以下截屏video。

迁移

您需要为表创建迁移

您需要为关联的中间表创建迁移+由关联创建的中间表名称: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 

控制器Stuf

questions_controller.rb

 def new @question = Question.new @question.categories.build #Build a categories_questions so as to use fields_for end 

forms的东西

 = 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