3

I have two models. User and Account as follows

class Account < ActiveRecord::Base
  has_many :manages
  has_many :users, :through => :manages
end

class User < ActiveRecord::Base
  has_many :manages
  has_many :accounts, :through => :manages
end

If I were to use the rails console and create an instance of account by

acc = usr.accounts.build
acc.save

The following command would return the account instance created

usr.accounts

But the following command would not return the user instance

acc.users

Also when I look at the Join table, there is no entry created. What am missing here? I thought by using the build method that it automatically creates the join model entry.

Edward Huynh
  • 2,907
  • 1
  • 27
  • 26

2 Answers2

2

Try saving the user object instead.

acc = usr.accounts.build
usr.save
  • Nope, the idea is that saving the parent saves unpersisted associated children. See https://www.evernote.com/l/AAL0VZ4pfXFJtJEnMeSo2vL4XWn-tLDD7E0 where I show a parent (User) child (Feedbacks) relationship demonstrating it in a rails console. – Jonathan R. Wallace Jan 16 '16 at 18:25
  • Oops, sorry, after re-reading your link to that particular rails issue, I may have misinterpreted the question as my example was not for a has_many :through relationship. I didn't check that case. And I won't have time to look into this further any time soon. Great question, @neanderslob! – Jonathan R. Wallace Jan 17 '16 at 21:30
1

You'll get a full error report if you use .save! rather than .save

Using a has_many :through please try adding a model

class Manage < ActiveRecord::Base
  belongs_to :user
  belongs_to :account
end
Rabbott
  • 4,282
  • 1
  • 30
  • 53