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 %>
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:Be sure to change controllername to the name of the controller you are using. Then update your view as follows:
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
MyModelwith a name column, you could doThen just execute it in your action via: