xxyyxx
xxyyxx

Reputation: 2396

how can a call a method on created_at when using it as a condition for a query?

I want to make this query:

sector.posts.count(:conditions => {:created_at.month => 1..3})

However, it returns:

NoMethodError: undefined method `month' for :created_at:Symbol

But if I do post.created_at.month in the console, it returns the integer value for the month. How would I accomplish the query that I am trying to make?

Upvotes: 1

Views: 171

Answers (2)

user2191327
user2191327

Reputation: 374

You can use the count method in this case. More on sql conditions.

What you do is call the count method as so:

sector.posts.count(conditions: 'MONTH(created_at) in (1,2,3)')

or a better way of doing this:

sector.posts.where('MONTH(created_at) in (1,2,3)').count

Upvotes: 2

mindtonic
mindtonic

Reputation: 1395

You are attempting to call a method on the symbol :created_at in your query. In your console example, you are calling the method against an ActiveRecord object.

If you are trying to get the results from within a date range, use a BETWEEN query (at least on Mysql or Postresql) and set the beginning and end dates for the range.

sector.posts.where(["'posts.created_at' BETWEEN ? AND ?", Date.new(2013,1,1), Date.new(2013,3,31)])

You can also use the beginning_of date methods, such as beginning_of_quarter if you need your queries to be dynamic. They're pretty powerful.

Upvotes: 0

Related Questions