0

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

<%= f.fields_for :categories do |categories_form| %>
        <%= categories_form.select "category_ids", Category.all.collect { |c| [c.description, c.id] }, {}, {:multiple => true, :size => 9} %>
    <% end %>

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

4

2 回答 2

1

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

于 2012-08-08T09:28:29.433 回答
0

迁移

您需要为表创建迁移

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

于 2012-08-08T14:25:43.370 回答