【问题标题】:Submit Button Calling A Method提交按钮调用方法
【发布时间】:2013-10-01 12:39:42
【问题描述】:

我是 Ruby on Rails 的新手,我正在尝试更新设备属性 (lastChangedBy),该属性将在单击提交按钮时将其值设置为用户的 IP 地址。我想做类似的事情:

 <%= form_for(@device) do |f| %>
 .
 .
 .
 <%= if click? ( f.submit "Commit Entries", class: "btn btn-primary" ) == true %>    
      <%= @device.lastChangedBy = request.remote_ip %>
 <% end %>

但我认为这是不可能的。我正在考虑使用“button_to”,但在网上搜索后,我对如何使用它感到非常困惑。我尝试做类似的事情:

 <%= button_to "Commit Entries", action: "setIp" %>

然后在 DevicesController 和 helper.rb 中(因为我不确定它会在哪里调用该方法)我做了一个简单的方法:

 def setIp
      Device.find(params[:id])
  @device.lastChangedBy = request.remote_ip
 end

但我完全迷路了。有人可以帮助我。如果你是具体的,那就太棒了!

【问题讨论】:

    标签: ruby-on-rails ruby button methods ruby-on-rails-4


    【解决方案1】:

    由于您提到您不确定如何使用 button_to 调用函数,并且您的控制器中已经有一个方法,您可以通过向视图的 button_to 添加一些字段来按如下方式处理它。通过这种方法,您还可以删除表单。

    =button_to 'SetIp', {:controller => "your_controller", 
         :action => "setIp", :id => your_model.id}, {:method => :post }
    

    在你的 routes.rb 中

    resources :your_controller do    
        post :setIp, :on => :collection    
    end
    

    在 your_controller.rb 中

    def setIp
        device = Device.find(params[:id])
        device.lastChangedBy = request.remote_ip
        device.save!
    
        #Can redirect to anywhere or render any page
        redirect_to action: :index
    end
    

    【讨论】:

      【解决方案2】:

      如果您已经提交了表单,并且想要设置该参数,请在控制器中进行:

      class DevicesController < ApplicationController
      
        def update
          @device = Device.find(params[:id])
          @device.last_changed_by = request.remote_ip # Tada!
          if @device.update_attributes(params[:device])
            redirect_to @device
          else
            render 'edit'
          end
        end
      
      end
      

      根据您的应用进行调整,但这是基本理念。

      【讨论】:

      • 这正是我所需要的!非常感谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 2014-12-04
      • 1970-01-01
      • 2016-08-20
      • 2023-02-04
      • 1970-01-01
      • 2011-09-05
      相关资源
      最近更新 更多