开发者

Improving an ':has_many :through' association in order to retrieve data

I am using Ruby on Rails 3.0.10 and I would like to improve some code (keep reading for more information) that retrieves data from the database using an :has_many :through association.

In the model I have:

class Article < ActiveRecord::Base
  has_many :category_relationships

  has_many :categories,
    :through => :category_relationships,
end

I would like to improve the following code (that retrieves article categories objects "filter开发者_StackOverflow中文版ing" some of those by using a where statement) so to follow the "Ruby on Rails Way of doing things":

@articles.category_relationships.where(:comment_id => @comment.id).map{ |category_relationship| category_relationship.article_category }

How can\should I do that? Can\Should I "work" on the @articles.categories association in order to improve the above code? If so, how?


Can you use something like below?

@articles.categories.where(["category_relationships.comment_id = ?",
                            @comment.id])

If you are worrying about DRYness, maybe you could extract the where into the model.

class Article < ActiveRecord::Base
   has_many :category_relationships

   has_many :categories,
      :through => :category_relationships do
     def has_comment(comment_id)
       where(["category_relationships.comment_id = ?", comment_id])
     end
   end

end

@articles.categories.has_comment(@comment.id)


I think you need nested has_many :through relationship between Article and CategoryRelationship. Here is a plugin that I had once used successfully to achieve exactly what you are looking for.

https://github.com/ianwhite/nested_has_many_through

This blog post also discusses other approaches.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜