I am trying to write up a dynamic query to search for sent messages. I have written up something like this right off my head and i know it has more errors.
def create
scope :before, lambda { |value| where('created_at <= (?)', value) if value }
scope :after, lambda { |value| where('created_at >= (?)', value) if value }
scope :from, lambda { |value| where('from LIKE (?)', value) if value }
scope :to, lambda { |value| where('to LIKE (?)', value) if value }
scope :with_message, lambda { |value| where('message LIKE (?)', value) if value }
@report = SentMessage.create_before(params[:report][:before])
.created_after(params[:report][:after])
.from(params[:report][:from])
.to(params[:report][:to])
.with_message(params[:report][:with_message])
.all.reverse
respond_with(@report)
end
I get an error like this;
undefined method `scope' for #<ReportsController:0xde24d2c>
Thank you in advance.
After improving the code; I am now getting this;
undefined method `default_scoped?' for #<String:0xcfa2678>
Improved code looks like this;
scope :created_before, lambda { |value| where("created_at <= (?)", value) if value }
scope :created_after, lambda { |value| where("created_at >= (?)", value) if value }
scope :sent_from, lambda { |value| where("from like (?)", "%#{value}%").to_sql if value }
scope :sent_to, lambda { |value| where("to like (?)", "%#{value}%").to_sql if value }
scope :with_message, lambda { |value| where("message like (?)", "%#{value}%").to_sql if value }
and the controller action looks like this;
def create
@report = SentMessage.created_before(params[:report][:before])
.created_after(params[:report][:after])
.sent_from(params[:report][:from])
.sent_to(params[:report][:to])
.with_message(params[:report][:message])
.all.reverse
respond_with(@report)
end
and the new error is
undefined method `default_scoped?' for #<String:0xd4c928c>