创建用于导轨设置的表单

时间:2014-07-26 17:45:10

标签: ruby-on-rails ruby forms preferences form-helpers

在我的Rails应用中,我使用gem rails-settings保存用户的电子邮件通知设置。我尝试创建表单来更新用户的通知设置。它应该包含一组复选框,用户可以在其中选择要接收有关电子邮件通知的内容。

在rails-settings README中,没有关于如何将其与表单集成的示例。我发现的最接近的教程列在问题中:

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

但我不确定实际的表单元素在我的视图中会是什么样子。例如,如果我想创建一个看起来像这样的输入:

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

如何使用rails form helper生成此内容?

1 个答案:

答案 0 :(得分:1)

这就是我创建表单的方式。希望这有助于其他人。

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