0

私は Rails にかなり慣れていないので、自分の関連付けに Rails フレームワークを活用する方法をよりよく理解しようとしています。

私のアプリに固有のものではありませんが、構造は似ています。私の例では、標準のブログ アソシエイトを使用します。

モデル例:

class Author < ActiveRecord::Base
    has_many :posts, :through => :posts
end

class Post < ActiveRecord::Base
    belongs_to :author
    has_many :comments
end

class Comment < ActiveRecord::Base
    belongs_to :post
end

私の課題は、特定の作成者に属するすべてのコメントを選択したいということです。特定の投稿に関連付けられている投稿要素と著者要素を参照する方法を理解しています。

comment_author = Comment.first
puts comment_author.post.author.name

しかし、私が述べたように、特定の作成者に属するすべてのコメントを選択しようとしています。find_by_sql を実行することでこれを達成できますが、データベースの独立性を確保したいので、これを「Rails の方法」で実行したいと考えています。

ありがとう!

4

2 に答える 2

0

関連付けを使用できますhas_many :through

class Author < ActiveRecord::Base
    has_many :posts
    has_many :comments, :through => :posts
end
于 2012-04-07T14:04:58.740 に答える
0

@Femaref はあなたの質問に正確な回答を提供したので、それを受け入れる必要があります。私のは単なる補足です。


投稿者が投稿にコメントを残すことができる場合は、次のことを行うことができます。

class Author
  has_many :posts
  has_many :comments
  has_many :responses, through: :posts, source: :comments                           
end

class Post
  belongs_to :author
  has_many :comments
end

class Comment
  belongs_to :author
  belongs_to :post
end

が残したすべてのコメントを取得するにはsophia:sophia.comments

さんの投稿に残されたすべてのコメントを取得するにはsophia:sophia.responses

(特にと)のオプションをhas_many参照してくださいthroughsource

于 2012-04-07T15:07:33.770 に答える