Rails: editing serialized data in a form

I have a model that has one parameter, which is a serialized Hash. I want to be able to edit a hash in a form using the built-in rail functions. It almost works. If you fill out the form and submit it, the parameters will be correctly serialized, and in the controller the model will be built with the expected values. When it falls apart, I want the form to display the existing model: none of the values โ€‹โ€‹appear in the fields of the form.

My model looks like this:

class Search < ActiveRecord::Base serialize :params end 

And the form:

 <%= form_for @search do |f| %> <%= f.fields_for :params, @search.params do |p| %> <%= p.label :square_footage, "Square Footage:" %> <%= p.text_field :min_square_footage, :size => 10, :placeholder => "Min" %> <%= p.text_field :max_square_footage, :size => 10, :placeholder => "Max" %> <% end %> ... <% end %> 

And in the controller creation method:

 @search = Search.new(params[:search]) @search.params ||= Hash.new logger.info("search = #{@search.inspect}") 

In the magazines:

 search = #<Search id: nil, params: {"min_square_footage"=>"1200", "max_square_footage"=>"1500"}, created_at: nil, updated_at: nil> 

So you can see that the values โ€‹โ€‹get POSTED.

In my opinion, I added this line above the form to find out if I can at least access the values:

 <%= @search[:params][:min_square_footage] %> 

And I can.

So, if I can access the values โ€‹โ€‹in my view and the form successfully submits data to my controller, why can't my form display the data?

+2
ruby-on-rails activerecord serialization
Feb 05 '11 at 23:11
source share
2 answers

it works:

 <%= p.text_field :min_square_footage, :size => 10, :placeholder => "Min", :value => @search[:params][:min_square_footage] %> <%= p.text_field :max_square_footage, :size => 10, :placeholder => "Max", :value => @search[:params][:max_square_footage] %> 

but not perfect. rails should automatically plot shape values, right?

0
Feb 05 2018-11-11T00:
source share

I think you need an object-method relation for the values โ€‹โ€‹that will be populated by default on the form. Methods are called by Rails to fill out the form. You can write methods in the search model for two data min_square_footage and max_square_footage, such as

 class Search < ActiveRecord::Base serialize :params def min_square_footage params[:min_square_footage] unless params.blank? end def max_square_footage params[:max_square_footage] unless params.blank? end end 

and in the views:

 <%= form_for @search do |f| %> <%= f.label :square_footage, "Square Footage:" %> <%= f.text_field :min_square_footage, :size => 10, :placeholder => "Min" %> <%= f.text_field :max_square_footage, :size => 10, :placeholder => "Max" %> ... <% end %> 
0
Feb 07 '11 at 10:22
source share



All Articles