I am using Ruby on Rails 3.2.2 and I would like to retrieve / scope associated objects by "specifying" / "filtering on" an attribute value on those associated objects. That is, at this time I am using the following code:
class Article < ActiveRecord::Base
def self.search_by_title(search)
where('articles.title LIKE ?', "%#{search}%")
end
end
class ArticleAssociation < ActiveRecord::Base
def self.search_by_article_title(search)
joins(:article).where('articles.title LIKE ?', "%#{search}%")
end
end
In the above code the where('articles.title LIKE ?', "%#{search}%")
clause is repeated twice and so I thought that it may be improved with the DRY principle: is it possible to use the Article.search_by_title
method directly in the ArticleAssociation.search_by_article_title
method?
Typical use cases are:
ArticleAssociation.search_by_article_title("Sample string")
Article.search_by_title("Sample string")