Ruby on rails 提交按钮调用一个方法
我是RubyonRails新手,我正在尝试更新一个设备属性(lastChangedBy),每当单击submit按钮时,该属性就会将其值设置为用户的IP地址。我想做一些事情,比如:Ruby on rails 提交按钮调用一个方法,ruby-on-rails,ruby,button,methods,ruby-on-rails-4,Ruby On Rails,Ruby,Button,Methods,Ruby On Rails 4,我是RubyonRails新手,我正在尝试更新一个设备属性(lastChangedBy),每当单击submit按钮时,该属性就会将其值设置为用户的IP地址。我想做一些事情,比如: <%= form_for(@device) do |f| %> . . . <%= if click? ( f.submit "Commit Entries", class: "btn btn-primary" ) == true %> <%= @device
<%= form_for(@device) do |f| %>
.
.
.
<%= if click? ( f.submit "Commit Entries", class: "btn btn-primary" ) == true %>
<%= @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
class DeviceController
根据您的应用程序进行调整,但这是最基本的想法。如果您已经提交了表单,并且希望设置该参数,请在控制器中执行该操作:
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
class DeviceController
根据您的应用程序进行调整,但这是基本想法。因为您提到您不确定如何使用button_to调用函数,并且您的控制器中已经有一个方法,您可以通过在视图的button_to中添加一些字段来实现。通过这种方法,您还可以删除表单
=button_to 'SetIp', {:controller => "your_controller",
:action => "setIp", :id => your_model.id}, {:method => :post }
在你的路线上
resources :your_controller do
post :setIp, :on => :collection
end
在您的_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
由于您提到您不确定如何使用button_to调用函数,并且您的控制器中已经有了一个方法,您可以通过在视图的button_to中添加一些字段来实现它。通过这种方法,您还可以删除表单
=button_to 'SetIp', {:controller => "your_controller",
:action => "setIp", :id => your_model.id}, {:method => :post }
在你的路线上
resources :your_controller do
post :setIp, :on => :collection
end
在您的_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
这正是我所需要的!非常感谢你!这正是我所需要的!非常感谢你!