Ruby on rails Rails 3 cookies未定义
我有一个Rails 3博客。我希望每个帖子都有一个类似的按钮。单击它会将此操作保存到数据库中,并存储到用户的cookie中,该用户刚刚喜欢该帖子,因为该帖子再次禁止了相同的操作 为此,我写了一个简单的动作:Ruby on rails Rails 3 cookies未定义,ruby-on-rails,ruby,cookies,Ruby On Rails,Ruby,Cookies,我有一个Rails 3博客。我希望每个帖子都有一个类似的按钮。单击它会将此操作保存到数据库中,并存储到用户的cookie中,该用户刚刚喜欢该帖子,因为该帖子再次禁止了相同的操作 为此,我写了一个简单的动作: def like render :nothing => true id = params[:post_id] cookies.permanent[:like_history] ||= [] unless cookies.permanent[:like_history
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
但是当我尝试记录事情时,我得到了nil:NilClass的NoMethodError未定义方法“[]”。它指向这一行:cookies.permanent[:like_history]| |=[]就好像cookies.permanent不是数组一样
我在这里用cookies做错了什么吗?我想你在cookies中存储了一些东西。永久性的[:like_history],它不是数组。因此,使用to_a将数组设为nil或covert,然后尝试您的代码
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
一旦它起作用,删除你添加的那一行。我想你有一些东西存储在cookies中。永久的,永久的,非数组的。因此,使用to_a将数组设为nil或covert,然后尝试您的代码
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
一旦它起作用,删除您添加的那行。结果是,| |=操作符按rails标准计算为读取,这实际上是有意义的。你不能用cookies阅读。永久[:symbol],那是用来写的,你用cookies[:symbol]阅读。所以我把这行改成:
cookies.permanent[:like_history]=除非定义?cookies[:like_history]结果是,| |=操作符按rails标准计算为读取,这实际上是有道理的。你不能用cookies阅读。永久[:symbol],那是用来写的,你用cookies[:symbol]阅读。所以我把这行改成: cookies.permanent[:like_history]=除非定义?cookies[:like_history]cookies.permanent[:test]=“test”在应用程序的其他位置工作,例如在ApplicationController?cookies中。permanent[:test]=“test”在应用程序的其他位置工作,例如ApplicationController?