从模型访问Cookie [英] Accessing cookies from model

查看:63
本文介绍了从模型访问Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说尝试在Rails模型中访问cookie完全没有问题。

I have heard that trying to accessing cookies in a model in Rails is completely out of question.

但是我的情况是这样:

这是一个用于管理费用的小型应用程序。金额以欧元存储在数据库中,但是用户可以设置不同的货币,因此金额以用户想要的货币显示。为此,我重写了金额属性获取器和设置器,因此在获取和设置金额时要应用汇率。

It's a small application to manage your expenses. Amounts are stored in the database in euros, but the user can set different currencies so amounts are displayed in the currency the user wants. For this I have overridden the amount attribute getter and setter so when getting and setting the amount an exchange rate is applied.

我要存储的是用户选择的货币在Cookie中,重写的setter和getter在 Expense 模型中定义,显然:

The thing is that I am storing the user's chosen currency in a cookie and the overriden setter and getter are defined in the Expense model, obviously:

def quantity=(quantity)
    update_rates
    write_attribute(:quantity, @eu_bank.exchange(100*quantity.to_i, cookies[:currency], "EUR").cents)
end

def quantity
    update_rates
    c = read_attribute(:quantity)
    @eu_bank.exchange(c.to_i, "EUR", cookies[:currency]).cents/100.0
end

如何处理这种情况?

推荐答案

您可以访问控制器中的cookie,然后通过调用诸如 my_expences之类的东西将其立即传递给模型。 set_exchange_rate(cookie [:exchange_rate])在您的控制器中。

You can access the cookie in your controller, then pass it immediately to your model by calling something like my_expences.set_exchange_rate(cookie[:exchange_rate]) within your controller.

这篇关于从模型访问Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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