質問

2レベルのユーザー関係を持つ方法を見つけようとしています。

カメラマンにはクライアントがいます。クライアントには1人の写真家がいます。両方ともユーザーです。

次のようなユーザーモデルがあります:

class User < ActiveRecord::Base
  #authlogic

  has_many :client_associations, 
    :foreign_key => 'client_id', 
    :class_name => 'Association', 
    :dependent => :destroy

  has_many :clients, :through => :client_associations

  has_one :photographer_association, 
    :foreign_key => 'photographer_id', 
    :class_name => 'Association', 
    :dependent => :destroy

  has_one :photographer, :through => :photographer_association

end

そして、次のような関連モデル:

create_table "associations", :id => false, :force => true do |t|
    t.integer "photographer_id"
    t.integer "client_id"
end

class Association < ActiveRecord::Base
  belongs_to :client, :class_name => 'User'
  belongs_to :photographer, :class_name => 'User'
end

データを入力してコンソールを起動すると、user.clients.allまたはuser.photographerを実行すると空の配列が返されます。

何が間違っているのですか?

役に立ちましたか?

解決

foreign_keysを切り替える必要があります:

  has_many :client_associations, 
    :foreign_key => 'photographer_id', 
    :class_name => 'Association', 
    :dependent => :destroy

  has_many :clients, :through => :client_associations

  has_one :photographer_association, 
    :foreign_key => 'client_id', 
    :class_name => 'Association', 
    :dependent => :destroy

  has_one :photographer, :through => :photographer_association
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top