Question

I actually have a has_many through association in order to link parents and childrens from a users table. So here is what I've got in my models :

class User < ActiveRecord::Base
  has_many :parents_to_children, class_name: ParentsUser, foreign_key: :children_id
  has_many :parents, through: :parents_to_children, source: :parent

  has_many :children_to_parents, class_name: ParentsUser, foreign_key: :parent_id
  has_many :childrens, through: :children_to_parents, source: :children
end

class ParentsUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :parent, class_name: User
  belongs_to :children, class_name: User
end

My join table looks like as follow :

|----------------------------------------------------|
| id |  children_id  |  parent_id  |  relation_type  |
|----------------------------------------------------|

In order to save the data, I'm doing it (so far) :

resource.childrens << user if user

This works fine and well, but unfortunately, the relation_type is not saved (params[:user][:relation]).

So I've tried to do :

resource.childrens.build(childrens: [user], relation_type: params[:user][:relation]) if user

But I'm getting an error : unknown attribute: relation_type

Any ideas on how to achieve this in an elegant way?

Was it helpful?

Solution

You are missing accepts_nested_attributes_for. Write this in your User Model

accepts_nested_attributes_for :parents_user

This could resolve the Issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top