如何从视图调用控制器的方法? [英] How to call a controller's method from a view?

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

问题描述

我正在 Ruby-On-Rails 中开发一个小型应用程序.我想从视图中调用控制器的方法.此方法只会在数据库表中执行一些插入操作.这样做的正确方法是什么?我试过这样的事情,但显然方法代码没有执行:

I'm developing a small application in Ruby-On-Rails. I want to call a controller's method from a view. This method will only perform some inserts in the database tables. What's the correct way to do this? I've tried something like this but apparently the method code is not executed:

<%= link_to 'Join', method: join_event %>

推荐答案

link_to 方法调用中的方法选项实际上是 HTTP 方法,而不是操作的名称.这在传递 HTTP 删除选项时很有用,因为 RESTful 路由使用 DELETE 方法来触发销毁操作.

The method option in a link_to method call is actually the HTTP method, not the name of the action. It's useful for when passing the HTTP Delete option, since the RESTful routing uses the DELETE method to hit the destroy action.

您在这里需要做的是为您的操作设置一条路线.假设它被称为 join_event,将以下内容添加到你的 routes.rb:

What you need to do here, is setup a route for your action. Assuming it's called join_event, add the following to your routes.rb:

match '/join_event' => 'controllername#join_event', :as => 'join_event'

请务必将控制器名称更改为您正在使用的控制器的名称.然后按如下方式更新您的视图:

Be sure to change controllername to the name of the controller you are using. Then update your view as follows:

<%= link_to 'Join', join_event_path %>

_path 方法是根据路由文件中的 as 值生成的.

The _path method is generated based on the as value in the routes file.

要组织您的代码,您可能希望将插入内容封装到静态模型方法中.因此,如果您有一个名为 MyModel 且带有名称列的模型,您可以这样做

To organize your code, you might want to encapsulate the inserts into a static model method. So if you have a model called MyModel with a name column, you could do

class MyModel
  # ...
  def self.insert_examples
    MyModel.create(:name => "test")
    MyModel.create(:name => "test2")
    MyModel.create(:name => "test3")
  end
end

然后通过以下方式在您的操作中执行它:

Then just execute it in your action via:

MyModel.insert_examples

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

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