Ruby on rails “我怎么能?”;初始化";实例变量?
我只是想学习一下Rails 每次我通过邮递员发送get请求时,都会调用initialize方法,因此我无法维护@data数组,因为@data在每次请求时都会初始化。 有没有办法一次初始化@data,让create、update和destroy方法正常工作Ruby on rails “我怎么能?”;初始化";实例变量?,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我只是想学习一下Rails 每次我通过邮递员发送get请求时,都会调用initialize方法,因此我无法维护@data数组,因为@data在每次请求时都会初始化。 有没有办法一次初始化@data,让create、update和destroy方法正常工作 class BooksController < ApplicationController skip_before_action :verify_authenticity_token def initialize
class BooksController < ApplicationController
skip_before_action :verify_authenticity_token
def initialize
super
@data = [
{ title: "Harry Potter", author: "J.K Rowling" },
{ title: "Name of the wind", author: "Patrick Rothfuss" }
]
end
def index
render json: @data
end
def create
@data.push(params[:book])
render json: @data
end
end
class BooksController
因为我还不想使用任何数据库,并且知道每个请求都会创建BooksController的新实例。
要使此代码正常工作,以下更改可以解决此问题
class BooksController < ApplicationController
skip_before_action :verify_authenticity_token
@@data = [
{ title: "Harry Potter", author: "J.K Rowling" },
{ title: "Name of the wind", author: "Patrick Rothfuss" }
]
def index
render json: @@data
end
def create
@@data.push(params[:book])
render json: @@data
end
end
class BooksController
因为我还不想使用任何数据库,并且知道每个请求都会创建BooksController的新实例。
要使此代码正常工作,以下更改可以解决此问题
class BooksController < ApplicationController
skip_before_action :verify_authenticity_token
@@data = [
{ title: "Harry Potter", author: "J.K Rowling" },
{ title: "Name of the wind", author: "Patrick Rothfuss" }
]
def index
render json: @@data
end
def create
@@data.push(params[:book])
render json: @@data
end
end
class BooksController
如果要在请求之间保留任何内容,需要将其存储在某个位置:
- 数据库
- 基于内存的存储(Redis、Memcached)
- 文件系统
- HTTP cookies
- 查询字符串参数
多线程是另一个大问题,因为Rails服务器通常是多线程的,类变量不是线程安全的。如果要在请求之间持久化任何内容,需要将其存储在某个位置:
- 数据库
- 基于内存的存储(Redis、Memcached)
- 文件系统
- HTTP cookies
- 查询字符串参数
多线程是另一个大问题,因为Rails服务器通常是多线程的,类变量不是线程安全的。是的,您需要将其保存到数据库中。实例变量仅适用于该类的实例,每次发出新请求时,都会创建BooksController类的新实例,该类没有与itThanks@Mark关联的变量。我刚刚意识到每个请求都创建了一个新实例。在我进入数据库之前,这只是为了学习。是的,你需要将它保存到数据库中。实例变量仅适用于该类的实例,每次发出新请求时,都会创建BooksController类的新实例,该类没有与itThanks@Mark关联的变量。我刚刚意识到每个请求都创建了一个新实例。这只是为了在我进入数据库之前进行研究。这可以作为一种学习经验,但你应该从这个练习中吸取的是,你的数据应该放在你的课堂之外。Rails在这方面帮了你很多,如果你创建一个活动记录模型,它实际上会更容易。谢谢@Roland。我相信我会在几天内做到这一点。作为一种学习经验,这是可以的,但是你应该从这个练习中得到的是,你的数据应该放在你的课堂之外。Rails在这方面帮了你很多,如果你创建一个活动记录模型,它实际上会更容易。谢谢@Roland。我相信我会在几天内做到这一点。