1

我是 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

但我完全迷失了。有人可以帮助我。如果你是具体的,那将是惊人的!

4

2 回答 2

1

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

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

根据您的应用程序进行调整,但这是基本思想。

于 2013-09-25T19:22:49.767 回答
0

由于您提到您不确定如何使用 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
于 2013-09-25T19:32:19.877 回答