Rails 3: Filtering and scopes "cant convert hash to integer" problem
I have a "course" model, which has_many timeslots.
In the courses model, I have the following methods:
def available_timeslots
tsar开发者_JS百科ray = []
self.timeslots.map{ |t|
if t.available then
tsarray << t
end
}
tsarray
end
def earliest_slot
self.available_timeslots.first(:order => :starting_date)
end
What I'm trying to do now is get the earliest available timeslot for each course. Without the availability filter, @course.earliest_slot works fine. But if I try @course.available_timeslots.earliest_slot brings back a "can't convert hash into integer" message.
Any suggestions appreciated
Zabba's comment is right on the money. The available_timeslots method is returning an Array and you are calling the method first on that -- but that is not the same as calling the method first on the object that a Rails association returns.
I think you want to use scopes. So delete your available_timeslots method and add this to your Timeslot class:
scope :available, where(:available => true)
then in your earliest_slot method you can do
self.timeslots.available.first(:order => :starting_date)
and it will return the first available timeslot for the course referred to by 'self'.
(Note: I am making the assumption that 'available' is a boolean. If it is something else, change the where condition in the scope appropriately.)
精彩评论