How to call a controller's method from a view?

僤鯓⒐⒋嵵緔 提交于 2019-12-08 05:06:27

问题


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 %>

回答1:


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.

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 %>

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

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



回答2:


In addition to agmcleod's answer, you can expose controller methods to the view with ActionController::Base::helper_method:

class EventsController < ApplicationController
  helper_method :join_event

  def join_event(event)
    # ...
  end
end

But in this case, I think you're best off following his advice and moving this method to the model layer, since it's interacting with the database.



来源:https://stackoverflow.com/questions/10307581/how-to-call-a-controllers-method-from-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!