Ruby on Rails - 从模型访问控制器变量 [英] Ruby on Rails - Access controller variable from model
问题描述
我正在尝试访问在模型中的控制器中设置的实例变量.控制器是产品控制器,模型是产品模型.实例变量是另一个名为 account 的模型的实例.
I am trying to access an instance variable which is set in the controller in the model. The controller is the products controller and the model is the products model. The instance variable is a instance of another model called account.
实例变量为@current_account
当我运行代码时没有任何反应,我没有收到错误消息.有谁知道我在哪里可以找到有关模型中控制器中设置的访问实例变量的信息?
When I run the code nothing happens, I do not get an error. Does anyone know where I can find something read about access instance variables set in the controller from the model?
谢谢
伊夫
推荐答案
您通常不应该尝试从模型中访问控制器,因为我不会讨论一些高尚的问题.
You shouldn't generally try to access the controller from the model for high-minded issues I won't go into.
我解决了一个类似的问题:
I solved a similar problem like so:
class Account < ActiveRecord::Base
cattr_accessor :current
end
class ApplicationController < ActionController::Base
before_filter :set_current_account
def set_current_account
# set @current_account from session data here
Account.current = @current_account
end
end
然后只需使用 Account.current
这篇关于Ruby on Rails - 从模型访问控制器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!