在Rails 3中的哪里初始化变量 [英] Where to initialize variables in Rails 3

查看:86
本文介绍了在Rails 3中的哪里初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的3个月中,我一直在发现Ruby on Rails,我着迷了.但是有几件我不知道的事情是最好的方法.现在,我与一些变量的初始化堆栈在一起.所有的应用程序都在ajax上运行,因此所有实例变量应仅初始化一次.

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.

我曾尝试在applicationController中编写只运行一次的方法初始化",但问题是我正在访问尚未初始化的请求对象.

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.

我已经在applicationController中尝试了一个before_filter,但是即使我是ajax请求,它也会在我执行的每个请求中运行.

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.

我正在使用Ruby 1.8.7和Rails 3. 预先感谢

I'm using Ruby 1.8.7 and Rails 3. Thanks in advance

推荐答案

我假设,当您登陆页面并跳过同一页面上的所有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.

class ApplicationController < ActionController::Base

  before_filter :load_vars

  protected

  def load_vars
    unless request.xhr? #check if ajax call
       # do all your initialization here
    end
  end

end

这篇关于在Rails 3中的哪里初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆