Question : undefined method `each' for xxx error

Hi Experts,

I have a question displaying result set.
Currently, this works.

in controller:

 @attending_ip = AttendingIp.find_by_sql("SELECT ....")

in view:
<% @attending_ip.each do |u|  %>
...
...

But I am having this error when I do this:

in controller:

@attending_ip = AttendingIp.find(params[:id])

in view:

<% @attending_ip.each do |u|  %>

I tried this, but same error

<% for u in @attending_ip  %>

My guess is that @attending_ip = AttendingIp.find(params[:id]) only returns one row. If I do this <%= @attending_ip.first_name %> without <% @attending_ip.each do |u|  %>, it works. But I want to use this view for the def that returns multiple rows also. I hope my point is clear.
Why am I having this error?

thx,

Answer : undefined method `each' for xxx error

well you're right... find returns an instance of your object (which is not an array) so that is why trying to iterate through them fails.

Off the top of my head, two possible solutions are:

@attending_ip = AttendingIp.find(:all, :conditions => ["id = ?", params[:id]] )

or

make a partial and pass to it your value:

if @attending_ip.is_a?(Array)
   render :partial => "your_partial", :collection => @attending_ip
else
   render :partial => "your_partial", :object => @attending_ip
end


Random Solutions  
 
programming4us programming4us