MKK
MKK

Reputation: 2753

Why do I get undefined method error?

I get this error

undefined method `created_at' for #ActiveRecord::Relation:0x0000001c3f57e8

controller

    @user = User.find_by_username(params[:username])
    @post = @user.comment_threads

    if @post
        last_time = @post.created_at
        if Time.now - last_time <= 0.5.minute
            redirect_to messages_received_path 
            flash[:notice] = "You cannot spam!"   
            return
        end
    end

Upvotes: 1

Views: 145

Answers (2)

LPD
LPD

Reputation: 2883

@post = @user.comment_threads returns you an array of the post object. So created_at is attempted on the array as a whole and not on any post object.

This should help.

if @post
        last_time = @post.last.created_at
        if Time.now - last_time <= 0.5.minute
            redirect_to messages_received_path 
            flash[:notice] = "You cannot spam!"   
            return
        end
    end

Upvotes: 2

MurifoX
MurifoX

Reputation: 15109

Because this line @post = @user.comment_threads returns an object of ActiveRecord::Relation to you. Better put a .last or .first on the end of that sentence, so you can have a single Post object.

Upvotes: 3

Related Questions