alt
alt

Reputation: 13937

Rails 3 cookies undefined

I have a Rails 3 blog. I want every Post to have a "Like" button. Clicking on it will save this action to the database and store to cookies on the user who has just liked the Post (for disallowing same action again).

I wrote a simple action to do this:

def like
  render :nothing => true

  id = params[:post_id]
  cookies.permanent[:like_history] ||= []

  unless cookies.permanent[:like_history].include? id
    cookies.permanent[:like_history] << id

    @post = Post.find(id)
    @post.update_column(:likes, @post.likes + 1)
  end
end

But I'm getting NoMethodError (undefined method '[]' for nil:NilClass) when I try to log things. It points to this line: cookies.permanent[:like_history] ||= [] as if cookies.permanent isn't an array.

Am I doing something wrong with cookies here?

Upvotes: 1

Views: 819

Answers (2)

alt
alt

Reputation: 13937

Turns out, the ||= operator counts as "reading" by rails standards, which actually makes sense. You can't "read" with cookies.permanent[:symbol], that's for writing, you read with cookies[:symbol]. So I modified that line to read:

cookies.permanent[:like_history] = "" unless defined? cookies[:like_history]

Upvotes: 4

Rahul Tapali
Rahul Tapali

Reputation: 10147

I think you have something stored in cookies.permanent[:like_history] which is not an Array. So make it nil or covert to array using to_a and try your code.

def like
  render :nothing => true
  cookies.permanent[:like_history] = nil #or cookies.permanent[:like_history] = cookies.permanent[:like_history].to_a 

  id = params[:post_id]
  cookies.permanent[:like_history] ||= []

  unless cookies.permanent[:like_history].include? id
    cookies.permanent[:like_history] << id

    @post = Post.find(id)
    @post.update_column(:likes, @post.likes + 1)
  end
end

Once it works remove that line you added.

Upvotes: 0

Related Questions