Yes, it is alright to do that in update
method. Keep in mind, that since you are using strong-parameters
you shouldn't change the params
hash itself. Instead, change result parameters hash after it is whitelisted by strong-parameters
:
class TicketsController < ApplicationController
def update
# first, get whitelisted params
update_params = update_ticket_params
# then perform convertion
update_params[:value] = value_in_cents(update_params[:value])
@ticket.update(update_params)
# ...
end
private
def update_ticket_params
params.require(:ticket).permit(:value, ...)
end
def value_in_cents(value_in_dollars)
# TODO: convert dollars to cents
end
end
For better understanding of what I am talking about and possible problems see this (Modify ruby hash in place( rails strong params))
Another approach
You can convert value on the model level using virtual attribute. Whenever you set the virtual attribute (which is :value_in_dollars
), it will convert and assign value
attribute:
class Ticket < ApplicationRecord
attr_accessor :value_in_dollars
# whenever you set :value_in_dollars, it converts and assigns :value
def value_in_dollars=(value)
self.value = value_in_cents(value)
end
private
def value_in_cents(value_in_dollars)
# TODO: convert dollars to cents
end
end
Using this approach you can pass your value as value_in_dollars
from the form. The controller will look like this:
class TicketsController < ApplicationController
def update
@ticket.update(update_ticket_params)
# ...
end
private
def update_ticket_params
# expect 'value_in_dollars' value from the form, not 'value'
params.require(:ticket).permit(:value_in_dollars, ...)
end
end