notGeek
notGeek

Reputation: 1528

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

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

Upvotes: 1

Views: 7060

Answers (2)

Brandan
Brandan

Reputation: 14983

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.

Upvotes: 5

agmcleod
agmcleod

Reputation: 13611

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

Upvotes: 6

Related Questions