2013-09-25 182 views
0

我是新来的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 

但我完全失去了。有人能帮助我吗?如果你是特定的,这将是惊人的!根据您的应用

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 

调整,但是这是基本的想法:

回答

1

如果您已经提交表单,并要设置该参数,做到在控制器中。

+0

这正是我所需要的!非常感谢! –

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