Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Cookie Issue

I have the following new method in a ruby on rails app:

def new
   if cookies[:owner].empty?
     cookies[:owner] = SecureRandom.hex
   end
   @movie = Movie.new
   @movie.owner = cookies[:owner]
end

Basically, each new user is supposed to be issued a code which identifies them (though just by the cookie). So when the user creates a movie, the cookie that was created is stored in the owner field.

So two problems:

  1. Using the .empty? method when I delete the cookie from the browser, returns a undefined methodempty?' for nil:NilClass`

  2. When I do have a cookie already set in the browser, and then create a movie, the cookies[:owner] value is different from the @movie.owner code?

like image 867
infinity Avatar asked Dec 31 '14 22:12

infinity


1 Answers

  1. cookies[:owner] will either be nil (when it hasn't been set), or a String (when it's been set). The method you're looking for is blank?, instead of empty?

    2.1.0 :003 > nil.blank?
    => true
    
    2.1.0 :005 > "i'm not blank".blank?
    => false
    
    2.1.0 :006 > "       ".blank?
    => true
    
  2. As for your second problem: where do you call the save method? Do you have any callback on the Movie model that could rewrite the owner attribute?

like image 64
sjaime Avatar answered Sep 23 '22 10:09

sjaime