0

Before I installed the money-rails gem, I had this query in my controller:

@forecasts.where('max >= ?', @budget).limit(1)[0]

where :budget was an integer column in table forecasts.

After installing money-rails I renamed that column to :budget_subunits, entered monetize: :budget_subunits as: :budget in my :forecast model so that :budget is now a Money object. Now this query results in the following error:

PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "--- !ruby/object:Money fractional: 4000000000.0 currency: !ruby/object:Money::Currency id: :usd priority: 1 iso_code: USD name: United States Dollar symbol: $ alternate_symbols: - US$ subunit: Cent subunit_to_unit: 100 symbol_first: true html_entity: $ decimal_mark: . thousands_separator: ',' iso_numeric: '840' bank: !ruby/object:Money::Bank::VariableExchange rounding_method: rates: {} mutex: !ruby/object:Mutex {} " LINE 1: ...get_segments"."budget_source_id" = $1 AND (max >= '--- !ruby... ^ : SELECT "budget_segments".* FROM "budget_segments" WHERE "budget_segments"."budget_source_id" = $1 AND (max >= '--- !ruby/object:Money fractional: 4000000000.0 currency: !ruby/object:Money::Currency id: :usd priority: 1 iso_code: USD name: United States Dollar symbol: $ alternate_symbols: - US$ subunit: Cent subunit_to_unit: 100 symbol_first: true html_entity: $ decimal_mark: . thousands_separator: '','' iso_numeric: ''840'' bank: !ruby/object:Money::Bank::VariableExchange rounding_method: rates: {} mutex: !ruby/object:Mutex {} ') ORDER BY "budget_segments".max ASC LIMIT 1

I know I can just use the :budget_subunits column and compare that to the :max_subunits column, but wouldn't that defeat the whole purpose of using the money-rails gem?

Simply put, how can I use a Money object in activerecord queries?

allenwlee
  • 665
  • 6
  • 21

1 Answers1

2

Call cents on it to convert it into its cents value, and query on that.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • Thanks Ryan, I understand I can do that, but I felt like that defeated a big purpose of the money gem, which I thought was to seamlessly use the money object without subunits and having the gem convert it to subunits when it hits the database, and then auto-converting it back for the output. But if that's the only way to use it then I will. – allenwlee Mar 08 '14 at 19:38
  • No, the Money gem won't magically convert things for you. No gem should. – Ryan Bigg Mar 08 '14 at 22:47