Several associations in the model
I have a User model and an Account model. A user has many accounts, and the accounts are owned by one user. I have all the models and associations. Now I want to make one of these accounts the "master account". What's the best way to create associations? I added the primary_account_id column to the user table and set up associations like this, but it didn't work. Any advice?
class User < ActiveRecord::Base has_many :accounts has_one :primary_account, :class_name => "Account" end class Account < ActiveRecord::Base belongs_to :user end
I see this question a Rails model that has both has_one and has_many, but with some restrictions , which is very similar, and the second answer suggests what I was trying. However, when I use it, rails ignores the column I created and just grabs the first one in the table:
1) User Load (3.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] => #<User id: 1, email: "XXXXXXX@gmail.com", created_at: "2012-03-15 22:34:39", updated_at: "2012-03-15 22:34:39", primary_account_id: nil> u.primary_account Account Load (0.1ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."user_id" = 1 LIMIT 1 => #<Account id: 5, name: "XXXXXX", created_at: "2012-03-16 04:08:33", updated_at: "2012-03-16 17:57:53", user_id: 1>u = User.find(
source to share
So, I created a simple ERD and your problem is very simple, but I think I found a serious problem:
class User < ActiveRecord::Base has_many :accounts has_one :primary_account, :class_name => "Account", :primary_key => "account_pimary_id" end class Account < ActiveRecord::Base belongs_to :user end
To get the associations as they are, simply set
As long as it works, it will probably only cause problems. If an account is used as the foreign key for
and , you do not know if the account is a regular account or a master account without an explicit connection between and every time. A should only point to 1 column, in this case the user table . Then this is a live snapshot in the Account table.
@ Zabba's solution is smart but it just needs
has_one :primary_account, :class_name => "Account", :conditions => "users.primary_account_id = accounts.id", :include => :user
This means that all accounts are owned by the User and only 1 is marked as the main account. Nice and straightforward, avoiding fancy suggestions.
source to share