5 ruby methods controller ruby-on-rails view
基本上,我试图在用户点击链接(或按钮或某种类型的交互元素)时执行rails方法.
我试着把它放在视图中:
<%= link_to_function 'Add' , function()%>
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用.它最终只是简单地调用该函数而没有用户甚至点击"添加"链接.
我也尝试使用link_to,但这也不起作用.我开始认为没有一种干净的方法可以做到这一点.无论如何,谢谢你的帮助.
PS.我在ApplicationController中定义了方法,它是一个帮助方法.
Bob*_*bby 12
视图和控制器彼此独立.为了使链接在控制器内执行函数调用,您需要对应用程序中的端点执行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 %>
Run Code Online (Sandbox Code Playgroud)
在为ajax调用端点routes.rb添加POST路由时.
post '/ajax/sum' => 'MyController#ajax_sum'
Run Code Online (Sandbox Code Playgroud)
然后假设你有一个MyController类mycontroller.rb.然后定义方法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
Run Code Online (Sandbox Code Playgroud)
希望希望!