在模型文件中我有:
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 => :articleend
通过使用上面的代码,我可以这样做:
@comment.article_categorIEs.comment_related_to(@current_user)@comment.article_categorIEs.article_related_to(@current_user)
如何“干”范围方法,以使两者: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.
?
解决方法 我能提供的最好的是:scope :related_to,lambda { |user,context| tbl = context == :article ? :articles_categorIEs_article_relationships : :comments_articles_article_category_relationships where("#{tbl}.user_ID = ?",user.ID)}
这样就可以像你建议的那样给你@ comment.article_categorIEs.related_to(@ current_user,:article).但我同意马克斯·威廉姆斯的观点.这会不必要地混淆您的代码而没有真正的收益.
如果您真的希望进一步混淆代码,可以这样做:
def self.method_missing(method,*args) if method =~ /^(.*)_related_to$/ related_to(*args,) else super endenddef self.related_to(user,context) through = reflections[context.to_s.pluralize.to_sym].options[:through] tbl = reflections[through].options[:class_name].underscore.pluralize.gsub('/','_') where("#{tbl}.user_ID = ?",user.ID)end
请注意,我相信你的协会有一些错别字.可能应该是:
has_many :comment_article_category_relationships,:class_name => 'Comments::Articles::ArticlecategoryRelationship'has_many :comments,:source => :commenthas_many :article_relationships,:class_name => 'Articles::CategorIEs::ArticleRelationship'has_many :articles,:source => :article总结
以上是内存溢出为你收集整理的ruby-on-rails – DRY范围方法全部内容,希望文章能够帮你解决ruby-on-rails – DRY范围方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)