Reputation: 7391
How to fix price field before Rails does it? I'm getting this error:
undefined method
before_filter' for Class:0x007fdddc1549d0>`
Code:
class Item < ActiveRecord::Base
before_filter :update_fields
private
def update_fields
self.price = self.price.to_s.gsub(',', '.').to_f
# getting this results if called in "before_save"
# 5.77 => 5.77
# 5,15 => 5.00
end
end
Upvotes: 0
Views: 827
Reputation: 1087
This is how I solved the problem directly inside the model, without needing the before_filter callback inside the controller:
class Item < ActiveRecord::Base
before_validation :update_fields
private
def update_fields
[:field_1, :field_2, :field_3].each {|k|
self[k.to_sym] = self.attributes_before_type_cast[k.to_s].gsub(',', '.').to_f
}
end
end
Hope it helps!
Upvotes: 0
Reputation: 7391
So, I have solved this moving code to the controller:
# encoding: utf-8
class ItemsController < ApplicationController
before_action :fix_fields
private
def fix_fields
if params[:item].present?
params[:item][:price] = params[:item][:price].to_s.gsub(',', '.').to_f
end
end
Now if user enters:
5,75
saves 5.75
Upvotes: 2