我如何使用HABTM接受嵌套属性?

log*_*esh 5 ruby-on-rails has-and-belongs-to-many ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

我有两个型号用户和类别.

    class User < ActiveRecord::Base
        has_and_belongs_to_many :categories
        accepts_nested_attributes_for :categories
    end
Run Code Online (Sandbox Code Playgroud)

同样

    class Category < ActiveRecord::Base
        has_and_belongs_to_many :users
    end
Run Code Online (Sandbox Code Playgroud)

我有一个要求,我必须将类别添加到类别表并添加引用,以便我可以获得与用户相关的类别,但如果另一个用户输入相同的类别,那么我必须使用id而不是创建新一.我该怎么做?

还有一件事是我必须添加一个引用该类别类型的属性类型.例如

user1 ----> category1, category2
user2 ----> category2
Run Code Online (Sandbox Code Playgroud)

这里user1和user2有category2但是category2中的类型可能不同.那么我该如何维护呢?请帮我.我准备回答你的问题.

gab*_*lal 9

您必须使用has_many :through而不是HABTM将字段添加type到关系中:

class User < ActiveRecord::Base
  has_many :lines
  accepts_nested_attributes_for :lines
  has_many :categories, through: :lines
end

class Line < ActiveRecord::Base
  belongs_to :users
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :lines
  has_many :users, through: :lines
end
Run Code Online (Sandbox Code Playgroud)

type属性添加到类中Line.

参考:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

你需要两个控制器来完成其余的动作:userscategories

然后,在您的用户表单中,例如:

<%= nested_form_for @user do |f| %>
...#user attributes
<%= f.fields_for :lines do |line| %>
<%= line.label :category %>
<%= line.collection_select(:category_id, Category.all, :id, :name , {include_blank: 'Select Category'} ) %>
<%= line.label :type %>
<%= line.text_field :type %>
...#the form continues
Run Code Online (Sandbox Code Playgroud)

编辑 -

该类别独立于用户,并且用户独立于类别.

关联类Line将通过加入用户和类别category_iduser_id:

________          _______________
| user |          |     line    |          ____________
|----- |          |-------------|          | category |
| id   |----------| user_id     |          |----------|
| name |1        *| category_id |----------| id       |
| email|          | type        |*        1| name     | 
|______|          |_____________|          |__________|
Run Code Online (Sandbox Code Playgroud)

例:

git hub:https://github.com/gabrielhilal/nested_form

heroku:http://nestedform.herokuapp.com/