我正在使用Ruby on Rails 3.0.7,希望能够DRY(不要重复自己)我的作用域方法。
在模型文件中,我有:
class Articles::Category < ActiveRecord::Base
scope :article_related_to, lambda { |user| where('articles_categories_article_relationships.user_id = ?', user.id) }
scope :comment_related_to, lambda { |user| where('comments_articles_article_category_relationships.user_id = ?', user.id) }
has_many :comment_article_category_relationships
has_many :comments,
:class_name => 'Comments::Articles::ArticleCategoryRelationship',
:through => :comment_article_category_relationships,
:source => :comment
has_many :article_relationships
:class_name => 'Articles::Categories::ArticleRelationship',
has_many :articles,
:through => :article_relationships,
:source => :article
end
通过使用上述代码,我可以做到这一点:
@comment.article_categories.comment_related_to(@current_user)
@comment.article_categories.article_related_to(@current_user)
我该如何“DRY”范围方法,以便
:article_related_to
和:comment_related_to
都可以使用类似以下的内容?@comment.article_categories.related_to(@current_user)
# In order to pass the correct "context" 'article' or 'comment' I thought
# something like
#
# @comment.article_categories.related_to(@current_user, 'article')
# @comment.article_categories.related_to(@current_user, 'comment')
#
# but, maybe, there is a way to retrieve automatically that "context" so to
# write only one "DRYed" scope method.
?