使用 onclick 选项在视图中调用控制器方法 [英] Call a controller method in a view using onclick option

查看:41
本文介绍了使用 onclick 选项在视图中调用控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.我想调用一个控制器方法,它通过按钮或链接的 onklick 选项执行一些 sql 语句.

Hi I have the following problem. I would like to call a controller method which executes some sql statements by onklick option of a button or a link.

所以我在我的控制器中有一个发布"方法.它看起来像这样:

So I got a method "publish" in my controller. It looks sth like this:

def publish
  do execute sql statements
  flash[:notice] = 'sql statements executed.'
end

在我看来,我希望有一个按钮或链接可以像这样调用此方法:

And in my view I would like to have a button or a link to call this method like this:

<input type="button" onclick="<% controller.publish %>">

但我收到错误:

未定义的局部变量或方法

undefined local variable or method

我也尝试将其路由以使用此方法作为 :action.那也行不通.我现在搜索了一段时间,并通过将此方法设为 helper_method 找到了一些解决方案,尽管我再次遇到相同的错误.我对 Ruby 和 Rails 还很陌生,所以我希望你能帮助我.

I also tried to route it to use this method as :action. That did not work as well. I searched now for a while and found some solutions by making this method a helper_method, though I get the same error again. I'm pretty new to Ruby and Rails so I hope you can help me.

推荐答案

如果在您看来,您尝试了类似 <% controller.publish %> 的东西,那将调用 publish 动作 在视图呈现时,而不是在用户点击按钮时.

If, in your view, you try something like <% controller.publish %>, that will call the publish action when the view is rendered, not when a user clicks on the button.

你可以这样做:

  1. 创建一个在请求时调用 publish 的路由.例如,假设路由是 /publish.

  1. Create a route which will invoke publish when requested. For example, say the route is /publish.

在你看来,这样写:

onclick 属性的值必须是有效的 JavaScript,它将在按钮被点击时执行.在 JS 中,设置 window.location 会导致浏览器导航到不同的页面.在这种情况下,我们让浏览器导航到 /publish,这将导致您的 publish 操作被调用.您在 publish 中呈现的任何内容都会出现在浏览器中.

The value of the onclick attribute must be valid JavaScript, which will be executed when the button is clicked. In JS, setting window.location causes the browser to navigate to a different page. In this case, we are making the browser navigate to /publish, which will cause your publish action to be invoked. Whatever you render in publish will then appear in the browser.

在上面显示的 publish 代码中,您的 Ruby 语法是错误的,但我假设它只是一个示例,而不是您正在使用的实际代码.

In the code for publish which you show above, your Ruby syntax is wrong, but I am assuming that it is just a sample, not the actual code which you are using.

这篇关于使用 onclick 选项在视图中调用控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆