rails: editing serialized data in form

匆匆过客 提交于 2019-12-24 03:22:45

问题


I have a model that has one param that is a serialized Hash. I want to be able to edit the hash in a form using built in rails features. It is almost working. If you fill in the form and submit it, the params are correctly serialized and in the controller the model is built with the expected values. Where it falls apart is when I want the form to display an existing model: none of the values are displayed in the form fields.

My model looks like:

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's create method:

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

In the logs:

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

So you can see the values get POSTed.

In my view, above the form, I added this line to see if I could 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 POSTs the data to my controller, why can't my form display the data?


回答1:


this 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 is not ideal. rails should be wiring up the form values automagically shouldn't it?




回答2:


I think you need an object - method relationship for the values to be populated by default in the form. The methods are called by Rails to populate the form. You can write methods in Search model for the two datas min_square_footage and max_square_footage like this

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 %>


来源:https://stackoverflow.com/questions/4910326/rails-editing-serialized-data-in-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!