开发者

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 methodeach'`

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜