Named route helper in javascript - ruby-on-rails

If I'm doing some ajax stuff, I can get where a form 'normally' goes by grabbing its 'action' attribute:
'Sign Up': ->
post_url = $('#form').attr 'action' #=> users/sign_up (for example)
However, if I have this in my routes file:
post 'users/sign_up', to: 'users#create', as: :user_create
I'm wondering why I can't just do this:
'Sign Up': ->
post_url = <%= user_create_path %>
While erb tags are supported, I get this error when using a named route:
undefined local variable or method 'user_create_path'
Just wondering why this is happening... I mean using the named route helpers could be excellent. Although it may be less confusing to grab it from the form. Still think rails / coffeescript gem should implement this functionality.

The named routes helpers are probably not being included outside a controller/view.
You can access them in Rails.application.routes.url_helpers.user_create_path.
You could also use a gem like js-routes to do the job for you.

Related

How can overwrite the will_paginate urls? Will_paginate gem generate wrong url

I have a ruby on rails app and I use will_paginate to render my products from categories.
I have 3 routes for some action:
/category1
/category2
/category3
When I am on /category2 or /category3 page, the will_paginate generate URLs with /category1?page=nr_page NOT for /category1 url.
From what I noticed, if I change the order of the routes, will_paginate will generate URLs with the first route from my routes file.
will_paginate uses url_for and params to figure out the path for pagination. According to what you said, your routes file looks something like this:
get '/themes' => 'category#show_category', as: :all_themes
get '/templates' => 'category#show_category', as: :all_templates
get '/design-system' => 'category#show_category', as: :all_design_system
When you add `<%= self.params.inspect %> to your view. you will see something like this (maybe with more params in the hash):
<ActionController::Parameters {"controller"=>"category", "action"=>"show_category"} permitted: false>
This means that will paginate takes these parameters and uses them in the url_for method. The call looks like this:
url_for controller: 'category', action: 'show_category', page: 123
it doesn't see the current path in the browser, only the controller and action names. In this case it goes through all of the routes from the top until it finds first defined rule for given controller and action and takes the url from this rule. This means it will always use the URL for the first defined category in your list.
Possible solutions
Define different actions for every category. It will work fine for you if you want to use it this way
get '/themes' => 'category#themes', as: :all_themes
get '/templates' => 'category#templates', as: :all_templates
get '/design-system' => 'category#design_system', as: :all_design_system
Define one route with the parameter
get '/category/:category' => 'category#show_category', as: 'show_category'
and then in your views or controller use following links:
show_category_path(category: 'themes')
Just URLs will not look as nice as before.

Rails: link_to only if route exists

I'm writing a Rails Engine and in one of my views I'd like to create a link to main_app if a named route exists.
I will give an example to clarify the question:
The Main application may or may not define in routes.rb:
resources :my_resource, only: :index
In my rails engine I need to add a link to my_resource_path only if main_app defined that route. I think it should be something like the following:
<%= link_to "Link", main_app.my_path if my_resource_path_exists? %>
I tried:
<%= link_to "Link", main_app.my_resource_path if
main_app.respond_to?(:my_resource_path) %>
but, when the path does not exist, that raises NoMethodError:
undefined method `my_resource_path' for #<Module>
How my_resource_path_exists? method could be implemented? I'm using ruby 2.2 and rails 4.2
The question is related to: Determine if path exists as route in Rails controller
But in this case, I have a named route (my_resource_path), so I need something slightly different, but can't figure out by myself.
I found a solution wich does not require to recover from fail. It's possible to check if the route is defined using url_helpers:
Rails.application.routes.url_helpers.method_defined?(:my_path)
So, the code could be written like that:
<%= link_to "Link", main_app.my_resource_path if
Rails.application.routes.url_helpers.method_defined?(:my_resource_path) %>
You could either use main_app.try(:my_path) or rescue NoMethodError to return false.

understanding passing rails parameters between controllers

I am just starting to wrap my head around parameters in rails. I am currently working on a project that isn't accessible to the public, so keeping params secure isn't exactly a priority in this case.
I have a link_to to a different controller action that requires an object id to fulfil the controller action.
=link_to "Barcode", print_barcode_label_admin_items_path(:item_to_print => { :article_id => article.id })
Then in the relevant controller
def print_barcode_label
if params[:item_to_print][:article_id].present?
return if force_format :pdf
..........
private
def params_document
params.require(:document).permit!
end
As I was writing the code for this controller I am certain the parameters were being passed (I am using the better-errors gem to debug along the way so I could see them being passed in the request parameters hash). But now, not sure what I have done, but i get the error
undefined method `[]' for nil:NilClass
failing at line two in my above controller action. I am sure there is something really basic I am missing. What is it? Is there a more favourable way of doing this?
Update
So I started playing with other possible solutions, and one is naming a route that specifically carries the parameter
get 'print_barcode_label/:article_id', to: 'documents#print_barcode_label', as: 'print_barcode_label'
This seems a more robust and sensible approach. Howeever, despite passing the variable in the link, like this
=link_to "Barcode", print_barcode_label_admin_items_path(article.id)
Gives a no route matches error
No route matches {:action=>"print_barcode_label", :controller=>"admin/documents"} missing required keys: [:article_id]
It is hard to answer this question without seeing more code with some context. But if you want to do rails way you should propably create custom action on document resource.
In your routes.rb:
namespace :admin do
resources :documents
get :print_barcode_label, :on => :member
end
end
And then you can create link to this action:
= link_to 'Barcode', print_barcode_label_admin_document_path(article)

Cant create a link to named routes

I want to create a link to a named route
My routes.db have the following rule
match '/tablero', to: 'tablero#index',via: 'get' , as: 'tablero_main'
I can see the route using rake routes
tablero_main GET /tablero(.:format) tablero#index
But when i use the link_to as follows i get the "undefined local variable or method `tablero_main'" error.
<%= link_to "Tablero",tablero_main %>
Is there anything else i am missing?
You need to append path to the method name, like so:
<%= link_to "Tablero", tablero_main_path %>
Routes
To help you further, you'll need to also consider the role of resources in your routes
As Rails uses a resourceful routing infrastructure, every route you create should be based around a resource. In your case:
#config/routes.rb
resources :tablero, only: :index #-> domain.com/tablero
Admittedly, this will give you the path tablero_index_path, rather than tablero_main_path, but it ensures your routes are not only DRY, but also extensible. Nothing worse than having 100's of "match routes in a route file.
--
Helpers
After that, remember to use the correct route_path helper:
Each "route" path is basically just a helper method (which builds a URL for you). When using link_to, you need to reference the path helper directly. You didn't do this, which lead Rails to come back with the undefined method error

What does xxxx_path mean in ruby on rails

I try to add new controller and model use name foo and foos_controller, hope foos_path can redirect. Doesn't work.
A origin code here (working):
href="<%= contacts_path %>"
After I add new controller and model follow name convention I try use the same (Not working):
href="<%= foos_path %>"
And this contacts_path is not defined anywhere else in rb project.
what does xxxx_path mean and how to use it?
Rails follows convention to handle roots of application
when we execute this command
rails g scaffold foo
it generates routes along with your model, controller and views.
it generates a line in routes.rb as
resources :foo
this line makes you access all the actions of your controller
for example:
foos_path: # redirects you to the index page of your foos controller
new_foo_path: # redirects you to the create page of your foos controller etc.,
please go through this link for reference: http://guides.rubyonrails.org/routing.html
If you go to your terminal and type rake routes, it will list your currently defined routes. On the left side you'll have their prefix. For example, contacts might route to the index action in ContactsController.
The path suffix is a way of referring to those routes inside your code.
If foos_path is giving you an error, that means you either have not yet defined that route for the resource, or you have but it is called something else (if you defined it manually with the as: option).
More info can be found in the Rails Guide for Routing.
You'll be best reading up on this documentation
Path Helpers
Basically, the path_helpers of Rails are designed to help you define routes for your links etc in the most efficient way possible.
The bottom line is the path helper will take routes defined in your config/routes.rb and then allow you to call them dynamically - IE:
#config/routes.rb
resources :photos #-> photos_path
The path names are typically from your controllers, allowing you to route to the various actions inside them. As Rails is built around being a resourceful structure, it will by default create routes for the "standard" controller actions:
link_to
In order to use the path helpers effectively, you'll be best using the rake routes command in cmd, or by simply typing an invalid url into your app's address bar
I notice you're using the standard HTML <a href=""> tag in your question. You'll be much better suited to using the link_to helper of Rails:
<%= link_to "text", your_path %>

Resources