我有一個用戶模型和一個帳戶模型。用戶擁有多個帳戶,並且這些帳戶屬於一個用戶。我有所有的模型和協會。現在我想讓其中一個帳戶成爲「主帳戶」。建立關聯的最佳方式是什麼?我在我的用戶表中添加了一個primary_account_id列,並設置了這樣的關聯,但它不起作用。有小費嗎?模型中的多個關聯
class User < ActiveRecord::Base
has_many :accounts
has_one :primary_account, :class_name => "Account"
end
class Account < ActiveRecord::Base
belongs_to :user
end
編輯
我看到這個問題Rails model that has both 'has_one' and 'has_many' but with some contraints這是非常相似,第二個答案讓我嘗試了建議。然而,當我使用它軌忽略了我所做的列,只是抓住表中的第一個:
>> u = User.find(1)
User Load (3.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
=> #<User id: 1, email: "[email protected]", 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>
>>
可能:'has_one:primary_account,:class_name =>「Account」,:conditions =>「users.primary_account_id = accounts.id」'。 – Zabba 2012-03-26 01:03:20
好猜,但沒有:'帳戶加載(0.2ms)SELECT「accounts」。* FROM「accounts」WHERE「accounts」。「user_id」= 1 AND(users.primary_account_id = accounts.id)LIMIT 1 SQLite3 :: SQLException:no such column:users.primary_account_id:SELECT「accounts」。* FROM「accounts」WHERE「accounts」。「user_id」= 1 AND(users.primary_account_id = accounts.id)LIMIT 1' – jasonlfunk 2012-03-26 01:10:42