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/
source share