How can I use nested attributes using HABTM?

I have two models User and Category.

class User < ActiveRecord::Base has_and_belongs_to_many :categories accepts_nested_attributes_for :categories end 

similarly

  class Category < ActiveRecord::Base has_and_belongs_to_many :users end 

I have a requirement when I have to add categories to the category table and add a link so that I can get categories related to the user, but if another user is in the same category, then I should use the identifier instead of creating a new one. How can i do this?

And one more thing: I need to add an attribute type that relates to the category type. eg

 user1 ----> category1, category2 user2 ----> category2 

here user1 and user2 have category2, but the type in category2 may be different. So how can I save this? please, help. I am ready to answer your question.

+4
source share
1 answer

You should use has_many :through instead of HABTM to add a type field to the relation:

 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 

Add the type attribute to the Line class.

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

You will need two controllers with sedative 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 

EDIT -

The category is independent of the user, since the user is independent of the category.

The Line association class joins users and categories through category_id and user_id :

 ________ _______________ | user | | line | ____________ |----- | |-------------| | category | | id |----------| user_id | |----------| | name |1 *| category_id |----------| id | | email| | type |* 1| name | |______| |_____________| |__________| 

Example:

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

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

+9
source

Source: https://habr.com/ru/post/1500156/


All Articles