Creating form for rails-setting

2019-06-04 03:50发布

问题:

In my Rails app, I'm using the gem rails-settings to save a user's email notification settings. I'm trying to create a form to update a user's notification settings. It should consist of a set of checkboxes where the user selects what they want to receive email notifications about.

In the rails-setting README, there are no examples of how to integrate it with a form. The closest tutorial I found was listed in the issues:

https://github.com/ledermann/rails-settings/issues/46

But I'm not sure what the actual form element would look like in my view. For example, if I wanted to create an input that looked something like this:

<input name="settings[email][comments]" type="textbox" value="1">

How do I generate this using a rails form helper?

回答1:

This is how I created the form. Hope this helps someone else.

edit.html.erb

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
   <h4>Email notifications</h4>
   <div>Receive email notifications when</div>
   <div class="notification_settings_container" style="margin-bottom: 30px;">
        <%= fields_for current_user.settings(:email) do |settings_fields| %>
            <div class="notification_checkbox">
               <%= settings_fields.check_box :comments %> someone comments on my project
             </div>
             <div class="notification_checkbox">
                <%= settings_fields.check_box :followed %> someone follows me
             </div>
             <div class="notification_checkbox">
                <%= settings_fields.check_box :featured %> my projects get featured
             </div>
             <div class="notification_checkbox">
                <%= settings_fields.check_box :remixed %> someone remixes my project
             </div>
             <div class="notification_checkbox">
                 <%= settings_fields.check_box :collaborator %> someone adds me as a collaborator on a project
             </div>
             <div class="notification_checkbox">
                  <%= settings_fields.check_box :favorited %> someone favorites my project
             </div>
             <div class="notification_checkbox">
                  <%= settings_fields.check_box :collectify %> my project gets added to a collection
             </div>
         <% end %>
   </div>

   <%= f.submit "Update", :class=>"btn btn-small btn-info submitButton" %>
<% end %>

registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  def update
    if params[:rails_settings_setting_object]
            params[:rails_settings_setting_object].each do |key, value|
                Rails.logger.debug('setting email setting ' + key + 'to ' + value=="1")
                current_user.settings(:email).update_attributes! key.to_sym => value=="1"
            end
            redirect_to :back, notice: "Update email preferences!"
     end
   end
end