Access an attribute in the find method

Hello everyone :slight_smile:

I need to access an attribute directly into a find. Is that possible?

For instance:

Topics.find(:all, :conditions => expiration_date-1.hour + " < NOW( )")

Here, expiration_date would be an attribute of Topics.

Thank you !

I think you’d do something like this:

Topics.find(:all, :conditions => [“expiration_date < ?”, + 1.hour])

See for more examples.


It helps, thanks!

But what if I have 2 conditions ?

For instance, is this possible?

Topics.find(:all, :conditions => ["expiration_date < ? AND attribute =", + 1.hours], yet_another_variable)

Thank you!

Topic.find(:all, :conditions => [“expiration_date < ? AND attribute = ?”, + 1.hour, yet_another_variable])

In other words, everything goes in the conditions array. The first element is the SQL fragment. Every other element is a value to be substituted for a ? in the SQL fragment. Rails will properly quote strings and dates.

Again, see the find docs [ ] for examples. Also, the Rails Guides [ ] are good, and the section on query conditions [ ] has more details.