How to get an array from a database in Rails3 even when there's only one record?
In Rails3, I have the following line:
@messages = Message.where("recipient_deleted = ?", false).find_by_recipient_id(@user.id)
In my view, I loop through @messages
and print out 开发者_Python百科each message, as such:
<% for message in @messages %>
<%= message.sender_id %>
<%= message.created_at %>
<%= message.body %>
<% end %>
This works flawlessly when there are several messages.
The problem is that when I have one message, I get an error thrown at me:
undefined method
each'`
How do I force rails to always return an array of messages even if there's only one message so that each
always works?
Thanks!
Try this:
@messages = Message.where(recipient_deleted => false, :recipient_id => @user.id)
@messages.each do |message|
<%= message.sender_id %>
<%= message.created_at %>
<%= message.body %>
end
I think you're problem is that you are nested things really weird. Both should be part of the where clause
精彩评论