Reputation: 1419
I have private method on controller
private
def set_address
@address = Address.find(params[:id])
end
def city_options
@city_options = []
if @address
@city_options = City.where(province_id: @address.province_id).collect{ |x| [x.name, x.id] }
end
end
And on views of _form.html.erb
<%= f.select :city_id, @city_options, { :prompt => I18n.t('prompt.select_city') }, class: 'select-city text address-city' %>
It's fine on new form and edit has right selected value, but when I encrypt the id in city_options
method
@city_options = City.where(province_id: @address.province_id).collect{ |x| [x.name, encrypted_id(x.id)] }
List of city is shown and value of id is encrypted but wrong selected a value of city, just selected id on top of list.
Upvotes: 0
Views: 75
Reputation: 838
Wrong value is selected because the saved city_id
do not match the encrypted_id
of any select list option.
To get over it you can use options_for_select
method. Try following if encrypted_id
method is a helper method
<%= f.select :city_id, options_for_select(@city_options, selected: encrypted_id(f.object.city_id)), { :prompt => I18n.t('prompt.select_city') }, class: 'select-city text address-city' %>
Check this link http://apidock.com/rails/v3.1.0/ActionView/Helpers/FormOptionsHelper/options_for_select
If encrypted_id method is a controller method, you have pass currently selected value by encrypting it from controller. Or you can use
helper_method :encrypted_id
in controller to make encrypted_id method available in view and can use above mentioned method
Upvotes: 0