Rails Regeneration Error

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

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

In principle, each new user should be issued a code that identifies them (although only cookies). Therefore, when a user creates a movie, the cookie created is saved in the owner field.

So, two problems:

  • Use empty? method, when I remove the cookie from the browser, returns a undefined method empty? 'for nil: NilClass`

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

+5
source share
2 answers
  • cookie [: owner] will be either nil (if it was not installed) or String (when it was installed). The method you are 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 
  • Regarding the second problem: what do you call the save method? Do you have a Movie model callback that could rewrite the owner attribute?

+8
source

You can also use this.

 def new if !cookies[:owner] cookies[:owner] = SecureRandom.hex end @movie = Movie.new @movie.owner = cookies[:owner] end 
+1
source

Source: https://habr.com/ru/post/1210199/


All Articles