allenwlee
allenwlee

Reputation: 685

Money-rails gem: How to use Money object in ActiveRecord query?

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?

Upvotes: 0

Views: 1537

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107728

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

Upvotes: 2

Related Questions