基本上,我试图在用户单击链接(或按钮或某种类型的交互元素)时执行 Rails 方法。
我试着把它放在 View 中:
<%= link_to_function 'Add' , function()%>
但这似乎没有用。它最终只是在用户甚至没有点击“添加”链接的情况下调用该函数。
我也用 link_to 试过了,但也没用。我开始认为没有一种干净的方法可以做到这一点。无论如何,感谢您的帮助。
附言。我在 ApplicationController 中定义了该方法,它是一个辅助方法。
最佳答案
View 和 Controller 是相互独立的。为了使链接在 Controller 内执行函数调用,您需要对应用程序中的端点执行 ajax 调用。该路由应调用 ruby 方法并返回对 ajax 调用回调的响应,然后您可以解释该响应。
举个例子,在你看来:
<%= link_to 'Add', '#', :onclick => 'sum_fn()' %>
<%= javascript_tag do %>
function sum_fn() {
/* Assuming you have jQuery */
$.post('/ajax/sum.json', {
num1: 100,
num2: 50
}, function(data) {
var output = data.result;
/* output should be 150 if successful */
});
}
<% end %>
在您的 routes.rb
中为您的 ajax 调用端点添加一个 POST
路由。
post '/ajax/sum' => 'MyController#ajax_sum'
然后假设您在 mycontroller.rb
中有一个 MyController 类。然后定义方法ajax_sum
。
class MyController < ApplicationController
# POST /ajax/sum
def ajax_sum
num1 = params["num1"].to_i
num2 = params["num2"].to_i
# Do something with input parameter and respond as JSON with the output
result = num1 + num2
respond_to do |format|
format.json {render :json => {:result => result}}
end
end
end
希望就是希望!
关于ruby-on-rails - 如何从按钮或链接单击的 View 调用 Rails 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21037611/