but if use similar code in my view, it does not work, e.g @posts = Post.find(:all, :conditions => [“created_at.year = ? and
created_at.month = ?”, params[:year], params[:month]])
end
can anyone explain this to me please?
The :conditions clause in ActiveRecord uses SQL, not Ruby. The string
interpolation (<%= … %>) in ERb uses Ruby, not SQL. So you need to
use both, depending on the requirements of the given library.
SELECT * FROM posts WHERE
YEAR(created_at) = ‘2007’ and
MONTH(created_at) = ‘02’
Your database responds with whatever is appropriate to that query. The
YEAR and MONTH function in that query are interpreted and execute by the
database, rails just passes it along. Rails has no idea what that query
really means, it just collects the result.
When you do:
<%= YEAR(post.created_at) %>
Rails will look for a ruby method called “YEAR” and send it an argument
of a Time object. Ruby does not find a method called “YEAR” and throws
an exception.