2017-03-01 26 views
1

我在我的conversations_controller以下Rails代码:NoMethodError(未定义的方法`created_at”的零:NilClass)

用户可以是:masterrookie

@conversations = current_user.master.conversations.all 
@conversations = @conversations.sort_by { |c| c.messages.last.created_at }.reverse 

但在运行此我得到了一个created_atno method error。 如果我做了puts这样的:

puts "Sorted: #{@conversations.map { |c| c.messages.last}}" 

这给了我以下响应:

Sorted: [#<Message id: 9, content: "some content", user_id: 3, conversation_id: 1, created_at: "2017-03-01 00:00:36", updated_at: "2017-03-01 00:00:36", attachment_url: []>, nil, #<Message id: 11, content: "new message", user_id: 3, conversation_id: 6, created_at: "2017-03-01 15:15:58", updated_at: "2017-03-01 15:15:58", attachment_url: []>] 

如果我得到created_at那么为什么我不能提取最后的消息created_At比较和分类?

在做一个简单的

puts "The conversations sorted are: #{@conversations.map { |c| c.messages}}" 

给了我以下响应:

The conversations sorted are: [#<ActiveRecord::Associations::CollectionProxy [#<Message id: 1, content: "Hey there! This is my first message.", user_id: 1, conversation_id: 1, created_at: "2017-02-28 23:57:46", updated_at: "2017-02-28 23:57:46", attachment_url: []>, #<Message id: 2, content: "Thank you for your message. I am a coach.", user_id: 3, conversation_id: 1, created_at: "2017-02-28 23:57:46", updated_at: "2017-02-28 23:57:46", attachment_url: []>, #<Message id: 9, content: "adsdadasd", user_id: 3, conversation_id: 1, created_at: "2017-03-01 00:00:36", updated_at: "2017-03-01 00:00:36", attachment_url: ["https://ace-up-www.s3.amazonaws.com/message-attachments%2Fbd450b1e-f85c-47ec-94c7-c539809f8d68%2Frecommendation-bg.jpg"]>]>, #<ActiveRecord::Associations::CollectionProxy []>, #<ActiveRecord::Associations::CollectionProxy [#<Message id: 10, content: "Add a new message", user_id: 8, conversation_id: 6, created_at: "2017-03-01 14:58:29", updated_at: "2017-03-01 14:58:29", attachment_url: []>, #<Message id: 11, content: "new message", user_id: 3, conversation_id: 6, created_at: "2017-03-01 15:15:58", updated_at: "2017-03-01 15:15:58", attachment_url: []>]>] 

正如你可以看到有一个空#<ActiveRecord::Associations::CollectionProxy []>这可能是越来越转换为nil。 任何帮助调试呢?

+0

数组中有'nil'值,在这里'... updated_at:“2017-03-01 00:00:36”,attachment_url:[]>,nil,#<消息ID:11 .. .',看到'nil'? – fanta

+0

@fanta你是对的,我在发布问题后发现了同样的事情,所以我编辑了我的问题以添加更多细节。 – anonn023432

+0

你为什么不尝试类似'@conversations = current_user.master.conversations.joins(:messages).order(“messages.created_at DESC”)'',这样你的代码会更快。 – fanta

回答

1

当您尝试获取会话最后一条消息的实际没有任何消息的创建属性时发生错误。

@conversations = current_user.master.conversations.joins(:messages) 
@conversations = @conversations.sort_by { |c| c.messages.last.created_at }.reverse 

通过加入与对话只有ATLEAST一个消​​息会话中的信息将被检索,因此由我认为这个问题得到解决。

相关问题