views:

24

answers:

1

This might be simple but I'm starting out with rails.

I have the following statement:

@subjects = Cartitem.find_by_cid(session[:customerid])

In my View I have some code like this:

<% @subjects.each do |d| %>
 <tbody>
  <tr>

All works when when the above query returns multiple rows. However, when above query returns only one row then I get an error in my View saying method each is not defined.

What is the way to avoid this? Do I need to have some if/else in my view?

+3  A: 

Probably

@subjects = Cartitem.find_all_by_cid(session[:customerid])

will work, because Rails documentation says, that line You gave:

@subjects = Cartitem.find_by_cid(session[:customerid])

will actually call:

Cartitem.find(:first, :conditions => ["cid = ?", session[:customerid]])

I don't think the solution with to_a (mentioned by user141146) will work at all because, object that is being returned is not an instance of any kind of QuerySet (e.g. like in Django) but pure model instance thus it probably wont has this method at all.

Dejw
You can ensure a list by doing something like [@subjects].flatten
EmFi