Reputation: 719
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:
Using the .empty? method when I delete 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 create a movie, the cookies[:owner] value is different from the @movie.owner code?
Upvotes: 5
Views: 914
Reputation: 35
You could also use this.
def new
if !cookies[:owner]
cookies[:owner] = SecureRandom.hex
end
@movie = Movie.new
@movie.owner = cookies[:owner]
end
Upvotes: 2
Reputation: 1500
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
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?
Upvotes: 9