ruby-on-rails – 我如何使用HABTM接受嵌套属性?
我有两个型号用户和类别.
class User < ActiveRecord::Base has_and_belongs_to_many :categories accepts_nested_attributes_for :categories end 同样 class Category < ActiveRecord::Base has_and_belongs_to_many :users end 我有一个要求,我必须将类别添加到类别表并添加引用,以便我可以获得与用户相关的类别,但如果另一个用户输入相同的类别,那么我必须使用id而不是创建新一.我该怎么做? 还有一件事是我必须添加一个引用该类别类型的属性类型.例如 user1 ----> category1,category2 user2 ----> category2 这里user1和user2有category2但是category2中的类型可能不同.那么我该如何维护呢?请帮我.我准备回答你的问题. 解决方法
您必须使用has_many:through而不是HABTM将字段类型添加到关系中:
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. ref:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association 您将需要两个具有其余操作的控制器:用户和类别 然后,在您的用户表单中,例如: <%= 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 编辑 – 该类别独立于用户,并且用户独立于类别. 关联类Line将通过category_id和user_id加入用户和类别: ________ _______________ | user | | line | ____________ |----- | |-------------| | category | | id |----------| user_id | |----------| | name |1 *| category_id |----------| id | | email| | type |* 1| name | |______| |_____________| |__________| 例: git hub:https://github.com/gabrielhilal/nested_form heroku:http://nestedform.herokuapp.com/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |