0

I have two entities Posts and Comments associated as follows

class Post < ActiveRecord::Base
  attr_accessible :title, :msg
  has_many :comments
end

class Comment < ActiveRecord::Base
  attr_accessible :msg
  belongs_to :post
  scope :search, lambda { |msg| where(arel_table[:msg].matches('%#{msg}%'))}
end

The scope :search now search only for comments(msg), I want to write another scope to search for posts(msg) in comments.

How to write this?

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

0

try the following (I favor class methods than scopes with lambdas because they look cleaner and are easier to read)

# comment.rb

def self.search(msg)
  where(arel_table[:msg].matches('%#{msg}%'))
end

def self.post_search(msg)
  joins(:post).where(Post.arel_table[:msg].matches("%#{msg}%"))
end
jvnill
  • 29,479
  • 4
  • 83
  • 86