2012-03-26 32 views
3

私はユーザーモデルとアカウントモデルを持っています。ユーザーには多くのアカウントがあり、そのアカウントは1人のユーザーに属します。私はモデルと団体をすべてセットアップしました。今はそのアカウントの1つを「プライマリアカウント」にしたいと思います。どのような関連付けを設定するための最良の方法は何ですか?私は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> 
>> 
+1

可能性があります: 'has_one:primary_account、:class_name =>「アカウント」、:条件=>「users.primary_account_id = accounts.id」です。 – Zabba

+0

アカウントの読み込み(0.2ms)SELECTアカウント "。* FROM"アカウント "WHERE" accounts "。" user_id "= 1 AND(users.primary_account_id = accounts.id)LIMIT 1 SQLite3 :: SQLException:列:users.primary_account_id:SELECT "accounts"。* FROM "accounts" WHERE "accounts"。 "user_id" = 1 AND(users.primary_account_id = accounts.id)LIMIT 1' – jasonlfunk

答えて

6

だから私は、単純なERDを作成し、あなたの問題は非常に簡単ですが、私は私が見つけたと思います深刻な問題:

simple erd

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 

それはusers.account_primary_id代わりのusers.idを使用するように、ちょうどhas_one :primary_account:primary_keyを設定し、あるとして関連付けを取得します。

これは機能しますが、問題を引き起こす可能性があります。アカウントのuser_ididaccount_primary_idの外部キーとして使用されている場合、毎回idaccount_primary_idの両方に明示的に参加することなく、アカウントが通常のアカウントまたはプライマリアカウントであるかどうかはわかりません。 foreign_keyは、1列のみを指す必要があります。この場合、ユーザーの表idです。アカウントのテーブルにまっすぐに入っています。

@Zabbaソリューションは、スマート一つですが、ちょうどこれは、すべてのアカウントがユーザーに属し、1つだけがプライマリアカウントとしてフラグが立てられていることを意味加入

has_one :primary_account, :class_name => "Account", :conditions => "users.primary_account_id = accounts.id", :include => :user 

ため:includeを必要とします。ニースとストレートフォワード、どこが不吉なことを避ける。

+0

ありがとうございました! --- – jasonlfunk

関連する問題