NoMethodError(未定义的方法`created_at'对于nil:NilClass)

时间:2017-03-01 15:26:34

标签: ruby-on-rails ruby-on-rails-4 controller nomethoderror

我的conversations_controller中有以下Rails代码:

用户可能是:masterrookie

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

但是在执行此操作时,我no method error获得了created_at。 如果我这样做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。 有没有帮助调试这个?

1 个答案:

答案 0 :(得分:1)

当您尝试获取创建于转化的最后一条消息的属性时发生错误,该消息实际上没有任何消息。

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

通过将消息与对话结合起来,只会检索与至少一条消息的对话,因此我认为问题得到解决。