Ruby on rails syntax

Hi everyone, simple syntax question that is confusing me.
I have the folowing method im my controller:

def archive
@posts = Post.find(:all, :conditions => [“YEAR(created_at) = ? and
MONTH(created_at) = ?”, params[:year], params[:month]])
end

which works fine.

but if use similar code in my view, it does not work, e.g

<%= YEAR(post.created_at) %>

i have to use this code in my view:

<%= post.created_at.year %>

But likewise, if use this line in my controller, it does not work:

def archive
@posts = Post.find(:all, :conditions => [“created_at.year = ? and
created_at.month = ?”, params[:year], params[:month]])
end

can anyone explain this to me please?

many thanks

Hi –

On Sat, 24 Feb 2007, Jon wrote:

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.

David


Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)

Jon wrote:

Thank you David, so the month functions being called are in fact
different functions?

Yes.

When you do this:

Post.find(:all, :conditions => [“YEAR(created_at) = ? and
MONTH(created_at) = ?”, params[:year], params[:month]])

Rails sends a query like this to the database:

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.

You probably want something more like:

<%= post.created_at.year %>

got it! thanks guys.

Thank you David, so the month functions being called are in fact
different functions?