Reputation: 1695
I have a datetime column in one of my tables (team_opps) called start_date.
I am trying to write methods in my model that allow me to classify them as Monday, Tuesday, etc... opportunities.
def self.friday_team_opps
where('WEEKDAY(start_date) = ?', 4)
end
In my view I am trying to call a .each on it.
<% TeamOpp.friday_team_opps.each do |team_opp| %>
<%= render team_opp, :team_opp => :team_opp %>
<% end %>
Error is:
SQLite3::SQLException: no such function: WEEKDAY: SELECT "team_opps".* FROM "team_opps" WHERE (WEEKDAY(start_date) = 4)
Thanks
Upvotes: 0
Views: 103
Reputation: 3999
First of all, you need to define the method on the TeamOpp class by defining the method as def self.friday_team_opps
.
Moreover, you can't call methods on the column since it would require ActiveRecord to load all the data in your table and then call the Ruby method on that data. What you can do is use direct SQL functions, like for example MySQL's WEEKDAY (monday = 0, tuesday = 1, etc.):
def self.friday_team_opps
where("WEEKDAY(team_opps.created_at) = ?", 4)
end
In SQLite, you can use the strftime function (sunday = 0, monday = 1, etc.):
def self.friday_team_opps
where('strftime("%w", "created_at") = "?"', 5)
end
Upvotes: 1
Reputation: 2228
If you want to make it a instance function then you should use it like this
def friday_team_opps
return self.start_date.strftime("%A")
end
Subsequently you will have to modify your view like this :
<% TeamOpp.select("start_date").each do |team_opp| %>
<%= team_opp.friday_team_opps() %>
<% end %>
Upvotes: 0
Reputation: 1502
You define it as an instance method
def friday_team_opps
And it should be defined as a class method
def self.friday_team_opps
Upvotes: 0