尝试连接两个表并显示正确的信息

时间:2013-11-14 18:50:01

标签: ruby-on-rails ruby

@followers = current_user.followers.joins(:received_messages).uniq.order("id DESC")

快速解释,它抓住当前用户关注者并将其与消息一起发送/接收。并且一次只显示一个。

我正在使用此功能在收件箱中显示“消息”,该部分工作正常,我希望通过最新发送的OR收到的消息ID来订购该收件箱。

现在我的观点看起来像这样,(这是一个混乱的地狱,我知道有一些方法让我在红宝石中更干净)

-if f.sent_messages.first && f.received_messages.first
  -if f.sent_messages.last.id > f.received_messages.last.id
    p This is running
    =image_tag f.avatar
    h2= f.uid
    p= f.sent_messages.last.body
    =link_to "Go To Conversation", conversation_path(:id => f.sent_messages.last.sender_id)
  -else
    =image_tag f.avatar
    h2= f.uid
    p= f.received_messages.last.body
    =link_to "Go To Conversation", conversation_path(:id => f.received_messages.last.receiver_id)
  end
-elsif f.sent_messages.first && f.received_messages.first == nil
  =image_tag f.avatar
  h2= f.uid
  p= f.sent_messages.last.body
  =link_to "Go To Conversation", conversation_path(:id => f.sent_messages.last.sender_id)
-elsif f.sent_messages.first == nil && f.received_messages.first
  =image_tag f.avatar
  h2= f.uid
  p= f.received_messages.last.body
  =link_to "Go To Conversation", conversation_path(:id => f.received_messages.last.receiver_id)

1 个答案:

答案 0 :(得分:0)

试试这个

-if f.sent_messages.any? || f.received_messages.any?
  =image_tag f.avatar
  %h2 = f.uid
  -unless f.sent_messages.empty? || f.received_messages.empty?
    -message,id = f.sent_messages.last.id > f.received_messages.last.id ? [f.sent_messages.last,f.sent_messages.last.sender_id] : [f.received_messages.last, f.received_messages.last.receiver_id]
  -else
    -message,id = f.sent_messages.last.nil? ? [f.received_messages.last,f.received_messages.last.receiver_id] : [f.sent_messages.last,f.sent_messages.last.sender_id]
  %p = message.body
  =link_to "Go To Conversation", conversation_path(:id => id)