Search code examples
ruby-on-railsruby-on-rails-4controllernomethoderror

NoMethodError (undefined method `created_at' for nil:NilClass)


I have the following Rails code in my conversations_controller:

A user may be : master or rookie.

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

But on running this I'm getting a no method error for created_at. If I do a puts like this:

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

this gives me the following response:

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: []>]

If I'm getting created_at then why can't I extract the last messages created_At to compare and sort?

On doing a simple

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

Gives me the following response:

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: []>]>]

As you can see there is an empty #<ActiveRecord::Associations::CollectionProxy []> which is probably getting translated to nil. Any help in debugging this?


Solution

  • The error occured when you tried to get the created at attribute of the converstions last message which actually dont have any messages with it.

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

    By joining the messages with the conversations only the conversation with atleast one message will be retrieved so by that i think the issue get fixed.