如何在HABTM中使用接受嵌套属性? [英] How can i use accepts nested attributes with the HABTM?
问题描述
我有两个模型User和Category.
I have two models User and Category.
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代替创建一个新的.我该怎么办?
i have a requirement where i have to add the categories to the categories table and add the reference so that i can get the categories related to user but if another user enters the same category then i have to make use of the id instead of creating new one. How can i do it?
还有一件事是我必须添加一个引用该类别类型的属性类型.例如
And one more thing is i have to add an attribute type which refers that category type. for example
user1 ----> category1, category2
user2 ----> category2
这里的user1和user2具有category2,但是category2中的类型可能不同.那么我该如何维护呢?请帮我.我准备回答你的问题.
here user1 and user2 has category2 but the type in category2 may differ.So how can i maintain this? please help me. I am ready to answer your question.
推荐答案
必须使用has_many :through
而不是HABTM
来将字段type
添加到关系中:
You must use has_many :through
instead of HABTM
to add the field type
to the relationship:
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 -通过关联有很多
您将需要两个具有轻松操作的控制器:users
和categories
You will need two controllers with the restful actions: users
and categories
然后,在您的用户表单中,如下所示:
Then, in your user form, something like:
<%= 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
编辑-
类别独立于用户,用户独立于类别.
The category is independent of user, as well as user is independent of category.
关联类Line
将通过category_id
和user_id
加入用户和类别:
The association class Line
will join users and categories through the category_id
and 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/
这篇关于如何在HABTM中使用接受嵌套属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!