Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Moe Khatib
Moe Khatib
5,293 Points

How to build simple_form for a hash field?

I have a model called UserSetting with user_id:integer and setting:text, The setting field is serialized as hash

I have another model called AppSettings with name:string, options:text The options field is serialized as Array

I am trying to build a simple_form for the UserSetting as follow:

<%= simple_form_for(@user_setting) do |f| %>
   <%= f.error_notification %>
  <div class="form-inputs">
<%= f.input :user_id %>
<% AppSetting.all.each do |setting| %>
    <%= f.input :setting, as: :select, collection: setting.options%>
<% end %>
</div>
 <div class="form-actions">
   <%= f.button :submit, 'Save Changes', class: 'btn-primary' %>
 </div>
<% end %>

I am un able to make simple_form export :setting as a hash

Here is a sample of what AppSetting data currently looks like:

#<ActiveRecord::Relation [#<AppSetting id: 1, name: "increase_prices_by", options: [0.05, 0.1, 0.15, 0.2, 0.25, 0.3], created_at: "2014-07-19 03:54:17", updated_at: "2014-07-19 03:54:17">, #<AppSetting id: 2, name: "hide_suggested_student_price", options: ["No", "Yes"], created_at: "2014-07-19 04:24:14", updated_at: "2014-07-19 04:24:14">]> 

I wanted to be saved in this format: {increase_prices_by: 0.05, hide_suggested_student_price: 'Yes', ....}

All the best :)

1 Answer

Moe Khatib
Moe Khatib
5,293 Points

After long a nigh I found the answer to my question:

First add the hash to the permitted params in the controller:

params.require(:user_setting).permit(:user_id).tap do |whitelisted|
    whitelisted[:setting] = params[:user_setting][:setting]
end

Next add the simple_field_for inside the simple_form in the view:

<%= f.simple_fields_for :setting do |setting| %>
    Send newsletter <%= setting.check_box :send_newsletter %>
    <% AppSetting.all.each do |s| %>
        <%= setting.input s.name  %>
    <% end %>

Done deal!