I have a table of events (in a sqlite3 database for what it’s worth) with a column called “when” that contains a timestamp detailing precisely when the event that particular row denotes is set to occur. Right now, I have
@events = Event.find(:all)
in my controller and I am using template helper methods to calculate where to place each event on my display page based on the day of the week it occurs on. For example:
<% if(event.when.wday == 6) %>
# DO SOMETHING
<% end %>
I want to abstract this logic to the controller however. My idea was to do the following:
@thursday_events = Event.find(:all, :conditions => ["when.wday=4"])
Obviously (I guess?) this didn’t work. Throwing the error “SQLite3::SQLException: near “when”: syntax error: SELECT * FROM “events” WHERE (when.wday=4)”.
I’m assuming this is because I tried to use a helper method within a find condition but I don’t know a better way to do this. Any advice? Thanks!
The conditions parameter needs to be a fragment of SQL.
is a fragment of Ruby code, so no go.
Try
SQLLite ref: http://www.sqlite.org/lang_datefunc.html
Added:
While more closely reading your post, I think you’re planning to send multiple instance variables (one per day of the week) from your controller to your view. That’s a good idea–moving logic out of the view. But, don’t do more dbms queries!
Each query has significant overhead. Eg:
Final comment:
Current best practice thinking is to move code into the models from controllers wherever reasonable. This is called “Fat model, skinny controller” In the above example, you could have a class-level method in the model create the individual instance variables. Or perhaps better, one hash that contains 7 values, each being an array of the records. Eg