Forum: Ruby on Rails for in loop with only one element not working

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dc372593c8ad1d324033652008f706ee?d=identicon&s=25 Ruby on Rails: Talk (Guest)
on 2009-06-04 22:59
(Received via mailing list)
Hi

I have the following code:

@lunchtimes = Lunchtime.find_by_dayname("#{todayname}")
for l in @lunchtimes do
    #    i = lunch.lunchfrom
    #    j = lunch.lunchto
    #    while i < j do
    #          id="#{session[:dateviewing]}/#{i.strftime('%H:%M:00')}/#
{lunch.therapist_id}"
    #          page[id].replace "<td class='lunch'><span
class='small'>LUNCH</span></td>"
    #    end
    #    i += 15.minutes
end

I've put the hashes in to see where the code is failing BTW!

All I'm trying to do is loop through the search results from
@lunchtimes. At the moment the query is returning only one record:

=> #<Lunchtime id: 4, therapist_id: 1, dayname: "Thursday", lunchfrom:
"2000-01-01 12:00:00", lunchto: "2000-01-01 13:00:00", effective:
"2009-06-04", created_at: nil, updated_at: nil>

And, as such I'm getting the following error:

NoMethodError (undefined method `each' for #<Lunchtime:0x21c1c70>):
    /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/
attribute_methods.rb:260:in `method_missing'
    /app/controllers/appointment_controller.rb:178:in
`__instance_exec0'

With more than one returned search results it works ...

I know it's probably something simple ... but can anyone tell me where
I'm going wrong. I'm sure similar code is working in other parts of my
program.

Thanks in advance for your help.

Darren
5f94b9b346c2aa648a80bc259978e5bc?d=identicon&s=25 Colin Law (Guest)
on 2009-06-04 23:29
(Received via mailing list)
2009/6/4 Ruby on Rails: Talk <dazzaroonie@gmail.com>:
>    #          id="#{session[:dateviewing]}/#{i.strftime('%H:%M:00')}/#
> @lunchtimes. At the moment the query is returning only one record:
>    /app/controllers/appointment_controller.rb:178:in
> `__instance_exec0'
>
> With more than one returned search results it works ...
>

I am not an expert in this but I understood that find_by_attribute
returned only the first matching record, in which case the result
would never be an array.  If you want to get all of them then you
should use find_all_by_attribute and the result will always be an
array, possibly with only one element.

I may well be wrong on this though.

Colin
This topic is locked and can not be replied to.