1

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

However this is my situation:

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.

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

How can I approach this situation?

dabadaba
  • 9,064
  • 21
  • 85
  • 155

1 Answers1

0

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.

Matt Stevens
  • 1,104
  • 1
  • 12
  • 24
  • Indeed, this is also the preferred pattern when accessing other controller-level objects like `session` and `params` - just pass them to model, keep controller thin. – Epigene Jun 14 '16 at 09:25