繁体   English   中英

Rails 3:使用提交按钮更新模型属性

[英]Rails 3: Using a submit button to update a model attribute

我有一个用户模型,其中包含带有布尔值的“电子邮件切换”列。 我想在我的视图中创建一个按钮,该按钮允许用户“打开”和“关闭”他们的电子邮件。 我无法使用“提交”按钮来更新“用户”模型中的值。

   <%= form_for :user do |f| %>
        <label>On</label>
        <%= f.radio_button :email_switch, true %>
        <label>Off</label>
        <%= f.radio_button :email_switch, false %>
        <%= f.submit "Save", :controller => "dashboard_emails", :action => "update", :method => "put" %>
    <% end %>


class DashboardEmailsController < ApplicationController
  before_filter :require_user

  def index
  end

  def update

  end

  private

  def require_user
    @user = @logged_in_user
  end


class User
  field :email_switch, type: Boolean, default: false
end

您需要将参数传递给form_for而不要传递给f.submit调用。 如果您将持久用户分配给@user ,则应该能够执行以下操作:

<%= form_for @user do |f| %>
    <label>On</label>
    <%= f.radio_button :email_switch, true %>
    <label>Off</label>
    <%= f.radio_button :email_switch, false %>
    <%= f.submit "Save" %>
<% end %>

当然,您需要config/routes.rb resources :usersconfig/routes.rb起作用。 然后,这应将PUT请求发送到/users/47 ,这将触发UsersController#update动作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM