2

(例として)has_many人の友人によるすべての投稿への関連付けを作成しhas_many :remote_postsたいperson > friends > person > posts.

..これが私がそれについて行く方法です

script/generate model post title:string person_id:integer
script/generate model friendship person_id:integer friend_id:integer
script/generate model person name:string

class Person < ActiveRecord::Base
  has_many :posts
  has_many :friendships, :foreign_key => 'friend_id'
  has_many :people, :through => :friendships
  has_many :remote_posts, :class_name => 'Post', :through => :people, :source => :posts
end
class Friendship < ActiveRecord::Base
  belongs_to :person
  #also has a 'friend_id' to see who the friendship is aimed at
end
class Post < ActiveRecord::Base
  belongs_to :person
end

# generate some people and friends
{'frank' => ['bob','phil'], 'bob' => ['phil']}.each {|k,v|
  v.each {|f| 
    Friendship.create(
      :person_id => Person.find_or_create_by_name(f).id,
      :friend_id => Person.find_or_create_by_name(k).id
    )
  }
}
# generate some posts
Person.all.each {|p|
  p.posts.create({:title => "Post by #{p.name}"})
}

今、

Person.first.friendships  # ..works
Person.first.people  # (friends) ..works
Person.first.posts # ..works
Person.first.remote_posts #....

...そして、このエラーが発生します..

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: people.person_id: SELECT "posts".* FROM "posts" INNER JOIN "people" ON "posts".person_id = "people".id WHERE (("people".person_id = 1))

外部キーエラーは別として、友情協会がまったく機能していないようです。:source => :posts関連付けが 2 回行われるため、これは のせいではないかと考えてpostsいました。

finder sql を書くこともできます (それが現在私が取り組んでいるものです) が、もっと早くこの方法で書きたいと思います。

これを機能させる方法のアイデアはありますか?

4

2 に答える 2

1

これはどう:

クラスで、FriendShip次を追加します。

has_many :posts, :through => :person


クラスでPerson、remote_posts を次のように変更します。

has_many :remote_posts, :class_name => 'Post',
         :through => :friendships, :source => :person
于 2009-10-20T15:57:50.640 に答える
0

has_many :throughネストされた関係はどうですか。これは私にとってはうまくいくようです:

class Friendship < ActiveRecord::Base
  belongs_to :person
  belongs_to :friend, :class_name => 'Person'
  has_many :posts, :through => :friend, :source => :posts
end
class Person < ActiveRecord::Base
  has_many :posts
  has_many :friendships, :foreign_key => 'friend_id'
  has_many :people, :through => :friendships
  has_many :remote_posts, :through => :friendships, :source => :posts
end

注: これにはこのnested_has_many_throughプラグインが必要です。(注: github リポジトリへの直接リンクは壊れているようですが、エラー メッセージにもかかわらず、そのリポジトリはそこにあります。)

于 2009-11-30T21:35:09.503 に答える