Get controller with a path - ruby-on-rails

At this time i'm trying to get the controller with a path as a parameter
Then what I need is a method that returns the controller, something like
<%= get_controller(users_path) %>
Thanks

Let me introduce you to ActionDispatch's recognize_path:
Rails.application.routes.recognize_path(users_path)[:controller]
=> "users"
Please note that if you are outside a controller or view (such as in a model or in the console, for example), you need to first include Rails.application.routes.url_helpers before passing named helpers to the method. String routes ("/users" in this case) will work in any case.

Related

Using helper methods in views

I'm having some trouble realising how the helper methods should be used in views. For example, take these parts of code:
Mycontrollers_helper.rb
module MycontrollersHelper
def destroy_everything
Model.destroy_all
redirect_to root_path
end
end
How should it be used in the view then ? Let's say adding the method to a button in the view:
<%= button_to 'Destroy all', destroy_everything, method => :post %>
Is just writing a method in the helper.rb file enough or does it require some additional lines in the controller it refers to ? Is this even the correct syntax for something like this ?
Helpers in rails actually view helpers. So they are meant to provide some help to render your views.
If you want to delete something, and then redirect to some action, just use a controller action for that.
I think you are taking about view helper, which you want to call from your view template.
You can call your view helper with the name of the method.
Calling destroy_everything will works fine if this helper is included in your controller.
Update:
If you write your helper method in application helper then you don't need to worry about load/ include the helper.

Rails - How to access a Request Parameter from view in a helper

How do you access a view's request parameter inside a Helper?
My view events/index7 sets the parameter date_selected:
<div><%= link_to 'View' , events_index7_path(:date_selected => date), :class => 'btn btn-mini'%></div>
My helper is app/helpers/calendar_helper.rb
Here's a pic of it at the point in the Helper I where I want to access it.
I tried this:
classes << "dayselect" if day == DateTime.strptime(params[:date_selected], "%Y-%m-%d")
I get this error:
undefined local variable or method `params' for #<CalendarHelper::Calendar:0x007f8d215671f0>
OR should I be passing the date to the helper in a different way?
Thanks for the help!
params is a controller method, belongs to ActionController:Metal http://api.rubyonrails.org/classes/ActionController/Metal.html#method-i-params
It's possible to let View to touch params by exposing this controller method as a helper.
class FooController < ApplicationController
helper_method :params
Then, in your view you can call this helper with params as argument. my_helper(params)
But, wait, this breaks MVC principle. View should not touch params at all. All these works should be done at controller level. What if the params is incorrect? You need controller to respond that, instead of passing that responsibility to view.
So, if you need to touch it in view, it's a smell. Review the whole process, there must be a better arrangement.

need to pass parameter from controller to .html.erb file

My controller code:
def description
product = #products.find(params(:id))
end
This is in the controller and I have to pass the product variable to description.html.erb. How can I do this?
It is giving me an ArgumentError in StoreController#description.
In general the way variables from the controller get passed to the views is by assigning them as an instance variable, which are variables defined with an # before it, e.g #products. If you want the product variable to be passed along, it has to be set as #product, like so:
#product = #products.find ...
In this particular case, you are getting an error raised before your view even is called. The only line in your controller action is throwing this.
Make sure that #products is actually being set. It's not being set in the #description method, so is it being set in a before_filter here? Is #products able to call #find? In Rails we often only see a model calling this method, e.g Product.find(params[:id]).
Further more, I see that you're accessing your params hash with regular brackets instead of square brackets. In Ruby you use square brackets. This alone may be what's causing the error. Try changing that to:
#product = #products.find(params[:id])
You can pass variables from controller to views using #
example in controller :
#my_var = 'toto'
in view
<%= #my_var %>

Use a params[:value] to reference a controller method in Rails

I currently have a form (using form_tag). One of the fields is a dropdown list of options. Each option value matches the name of a method in my controller. What I want to do is when the form submit button is clicked, it runs the controller method corresponding directly to the value selected in the dropdown field.
I've built a work-around right now, but it feels too verbose:
def run_reports
case params[:report_name]
when 'method_1' then method_1
when 'method_2' then method_2
when 'method_3' then method_3
when 'method_4' then method_4
else method_1
end
# each method matches a method already defined in the controller
# (i.e. method_1 is an existing method)
I had thought that it may work to use the dropdown option value to run the corresponding method in my controller through the form_tag action (i.e. :action => params[:report_name]), but this doesn't work because the action in the form needs to be set before the params value is set. I don't want to use javascript for this functionality.
Here is my form:
<%= form_tag("../reports/run_reports", :method => "get") do %>
<%= select_tag :report_name, options_for_select([['-- Please Select --',nil],['Option 1','method_1'], ['Option 2','method_2'], ['Option 3','method_3'], ['Option 4','method_4']]) %>
<%= submit_tag "Run Report" %>
<% end %>
Any suggestions?
Can I change my controller method to look something like this - but to actually call the controller method to run? I'm guessing this won't run because the params value is returned as a string...
def run_reports
params[:report_name]
end
WARNING: this is a terrible idea
You could call the method via a snippet of code like this in the controller:
send(params[:report_name].to_sym)
The reason this is a terrible idea is that anyone accessing the page could manually construct a request to call any method at all by injecting a request to call something hazardous. You really, really do not want to do this. You're better off setting up something to dynamically call known, trusted methods in your form.
I think you should rethink the design of your application (based on the little I know about it). You have a controller responsible for running reports, which it really shouldn't be. The controllers are to manage the connection between the web server and the rest of your app.
One solution would be to write a new class called ReportGenerator that would run the report and hand the result back to the controller, which would run any of the possible reports through a single action (for instance, show). If you need variable views you can use partials corresponding to the different kinds of reports.
As for the ReportGenerator, you'll need to be a little creative. It's entirely possible the best solution will be to have an individual class to generate each report type.

ruby on rails use variable in association call

i have a helper function which renders a partial and i pass a variable called method with it into the view...
when in view i use
<%= friend.method.profile.picture %>
the method variable can be either user or friend
and i get
wrong number of arguments(0 for 1)
i suppose there is a problem how i use the variable being passed into the association call... maybe i have to escape it somehow?
If I understand what you want, you are trying to dynamically call a function based on the value of a string argument called 'method'. Also, 'method' is an existing function in Ruby, (hence your error message about 'wrong number of args' vs 'undefined method'), so I would recommend renaming it in your code.
TLDR:
Rename your variable something like "person" (instead of 'method'), then
try some meta-programming to call the function using send:
friend.send(person).profile.picture
Here is the same answer as ~AmirRubin, but fleshed out more.
I am assuming that friend was the object, method was the helper, .profile is the method you want the helper to use.
Define your helper as:
def call_method(object, method_name)
object.send(method_name)
end
In your view call it as:
<%= call_method(friend, :profile).picture %>
Adjust this if my assumptions are wrong. If you need to send the method name (symbol) to the partial pass it in the locals.

Resources