Rails 3 中变量的初始化位置
在过去 3 个月里,我一直在探索 Ruby on Rails,并且对此着迷。但有几件事我不知道哪种是最好的方法。现在我正在堆栈一些变量的初始化。所有应用程序都通过 ajax 运行,因此所有实例变量只应初始化一次。
我尝试在 applicationController 中编写一个方法“initialize”,该方法仅运行一次,但问题是我正在访问尚未初始化的请求对象。
我已经在 applicationController 中尝试过 before_filter 但它会运行我所做的每个请求,即使它是 ajax 请求。
有谁知道如何使用请求对象中的值初始化实例变量?是的,可能是一个新手问题。
我正在使用 Ruby 1.8.7 和 Rails 3。 提前致谢
I've been discovering Ruby on Rails during the last 3 months and I'm fascinated. But several things I don't know which is the best way to do them. Now I'm stack with the initialization of some variables. All the application is running over ajax, so all the instance variables should be initialize only once.
I've tried writting a method 'initialize' in the applicationController which is run just once, but the problem is that I'm accesing the request object which is not initialized yet.
I've tried a before_filter in the applicationController but it is run every request I do, even if it is an ajax request.
Does anyone know how to initialize an instance variable with a value from the request object? Yes, probably a newbie question.
I'm using Ruby 1.8.7 and Rails 3.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设,您希望在登陆页面时执行初始化部分,并针对来自同一页面的所有 ajax 请求跳过它。
I assume, you would want to do the initialization part when you land on a page and skip it for all ajax requests from the same page.
如果您正在讨论的变量是从请求参数初始化的,则必须为每个请求初始化它。因此,正确的位置应该是前置过滤器。
请注意,ajax请求是从服务器端看到的正常请求,所以我不明白你的“偶数”。如果您正在检查的值来自请求参数,并且您在每个控制器/操作中都需要它,那么您确实在
ApplicationController
中进行了初始化,否则您只能在某些控制器中调用该过滤器(甚至 如果您需要在不同的控制器之间共享该方法,请在ApplicationController
中定义它,并仅在适当的控制器中执行
before_filter
调用。If the variable you're talking about is initialized from a request parameter it must need initialized for every request. So the right place to do that should be a before filter.
Note that an ajax request is a normal request seen from server side, so I don't understand your "even". If the value you're checking is coming from the request param and you need it in every controller/action you really do that initialization in the
ApplicationController
otherwise you could call that filter only in some controller (or even for some action only) with this syntaxIf you need to share that method across different controllers define it in
ApplicationController
and do thebefore_filter
call only in the appropriate controllers.您应该能够使用 before 过滤器来实现此目的,如下所示:
如果 before 过滤器仅适用于应用程序的一部分,则可以将其放置在特定控制器中,或者让它针对特定操作运行。
You should be able to achieve this using a before filter like so:
You could place the before filter in a specific controller if it only applies to one part of the application, or have it run for a particular action.