您必须使用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
将type
属性添加到类Line
。
参考: http: //guides.rubyonrails.org/association_basics.html#the-has-many-through-association
您将需要两个具有 restful 操作的控制器:users
和categories
然后,在您的用户表单中,类似于:
<%= 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
编辑 -
类别与用户无关,用户与类别无关。
关联类将通过andLine
加入用户和类别:category_id
user_id
________ _______________
| user | | line | ____________
|----- | |-------------| | category |
| id |----------| user_id | |----------|
| name |1 *| category_id |----------| id |
| email| | type |* 1| name |
|______| |_____________| |__________|
例子:
git 集线器:https ://github.com/gabrielhilal/nested_form
heroku: http: //nestedform.herokuapp.com/