2
votes

I have a rails app where users have children. So I had two models: :users and :children.

I used to have a one-to-many relationship (has_many / belongs_to), but I wanted to open it up to a many-to-many relationship where I could store variables about the relationship. So I changed the relationship to a "has_many through" relationship. I created a table called :relationships. A small caveat: I want the foreign_key for user to be :parent_id. Here is how I have them set up:

Schema:

create_table "relationships", :force => true do |t|
    t.integer  "child_id"
    t.integer  "parent_id"
    t.datetime "created_at"
.
.
.

create_table "users", :force => true do |t|
    t.string   "email",                                  :null => false
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
    t.string   "first_name"
    t.string   "last_name"
.
.
.

create_table "children", :force => true do |t|
    t.string   "name",                :null => false
    t.integer  "parent_id",           :null => false
    t.datetime "created_at",          :null => false
.
.
.

Class Definitions:

user.rb:

has_many :relationships, foreign_key: "parent_id"
has_many :children, :through => :relationships, foreign_key: "parent_id"

child.rb:

has_many :relationships, foreign_key: "child_id"
has_many :parents, :through => :relationships

relationship.rb:

belongs_to :parent, class_name: "User", :foreign_key => :parent_id
belongs_to :child, class_name: "Child", :foreign_key => :child_id

Now when I choose a specific user and try to get user.children, I get [] in response. If I try to add new children, it doesn't work either. I can define the parent and the child, but when it tries to save, It cannot associate the two. It doesn't see the parent, so I get the error:

*ActiveRecord::StatementInvalid (PG::Error: ERROR: null value in column "parent_id" violates not-null constraint*

If I switch the Class definitions back to a one-to-many setup, it accesses the children just fine. I don't understand what the problem is. Any help would be very appreciated.

Thanks

2

2 Answers

0
votes

How are you building the relationship? @user.children works for me with the given example when I create the relationship as follows:

@user.relationships.build(child_id: ...) 
-1
votes

in children table parent_id should be allowed to take null if you want create children as nested attributes.

Change

create_table "children", :force => true do |t|
  t.string   "name",                :null => false
  t.integer  "parent_id",           :null => false
  t.datetime "created_at",          :null => false
end

To

   create_table "children", :force => true do |t|
      t.string   "name",                :null => false
      t.integer  "parent_id"
      t.datetime "created_at",          :null => false
    end