Ich habe ein Benutzermodell und ein Account-Modell. Der Benutzer hat viele Konten und die Konten gehören einem Benutzer. Ich habe die Modelle und Assoziationen alle eingerichtet. Jetzt möchte ich eines dieser Konten zum "primären Konto" machen. Was ist der beste Weg, um die Assoziationen einzurichten? Ich habe eine Spalte primary_account_id zu meiner Benutzertabelle hinzugefügt und die Assoziationen so eingerichtet, aber es hat nicht funktioniert. Irgendwelche Tipps?Mehrere Zuordnungen in einem Modell
class User < ActiveRecord::Base
has_many :accounts
has_one :primary_account, :class_name => "Account"
end
class Account < ActiveRecord::Base
belongs_to :user
end
bearbeiten
Ich sehe diese Frage Rails model that has both 'has_one' and 'has_many' but with some contraints, die sehr ähnlich ist, und die zweite Antwort macht den Vorschlag, dass ich versucht. Jedoch, wenn ich es verwenden Schienen die Spalte ignoriert, die ich gemacht habe und greift nur die erste in der Tabelle:
>> 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>
>>
Möglicherweise: 'has_one: primary_account,: class_name =>" Konto ",: conditions =>" users.primary_account_id = accounts.id "'. – Zabba
Gut geraten, aber nein: 'Konto Laden (0.2ms) SELECT" Konten ". * FROM" Konten "WHERE" Konten "." Benutzer_ID "= 1 AND (users.primary_account_id = accounts.id) LIMIT 1 SQLite3 :: SQLException: keine solche Spalte: users.primary_account_id: SELECT "accounts". * FROM "accounts" WHERE "accounts". "User_id" = 1 UND (users.primary_account_id = accounts.id) LIMIT 1' – jasonlfunk