route is redirecting to wrong path - ruby-on-rails

This is what my routes currently look like:
which gives
On my homepage I have a create vacancy button
<%= link_to "plaats", new_employer_vacancy_path(:employer_id)%>
Which should be linked to the line from the first image
get '/employers/:employer_id/vacancies/new', to: 'vacancies#new', as: 'new_employer_vacancy'
In the vacancies_controller#new - create I have:
def new
#vacancy = Vacancy.new
#employervacancy = Employervacancy.new
end
def create
#vacancy = Vacancy.create(vacancy_params)
createEmployervacancy
redirect_to employer_vacancy_path(current_employer, #vacancy)
end
def createEmployervacancy
#employer = current_employer
Employervacancy.create(vacancy_id: #vacancy.id, employer_id: #employer.id)
end
But whenever I click the button I get redirected to some other method in my vacancies_controller that is totally irrelevant.
How is this even possible? Don't I clearly define that when that path is clicked he should go to vacancies#new? and not to vacancies#show_specific_employer_vacancies?
EDIT
After following the answers I am indeed being linked to the correct route.
First, it gave me this error.
After trying to pass the current_employer.id instead of #employer like suggested I got following error:

For your routes, you'd better to change into nested route for easily maintaining routes.
Remove these codes:
get '/employers/:employer_id/vacancies/:id', to:"vacancies#show_specific_employer_vacancies", as: "employer_vacancy"
get '/employers/:employer_id/vacancies/edit/:id' ...
get '/employers/:employer_id/vacancies/index' ...
get '/employers/:employer_id/vacancies/new' ...
path '/employers/:employer_id/vacancies/:id' ...
change into:
resources :employers do
resources :vacancies
end
Try to use basic routes here because you use standard simple form url. For example:
<%= simple_form_for(#employee, #vacancy) %>
The simple_form_for will generate url well if you use nested routes above.
Finally, in your link you have to add #employer_id
<%= link_to "plaats", new_employer_vacancy_path(:employer_id => #employer_id)%>
I hope this help you

Your router cannot tell the difference between your employer_vacancy and new_emplyer_vacancy routes because the :id parameter accepts anything. Because of this, when you point your browser to "/employers/5/vacancies/new", the route is taking your employer_vacancy route and assigning {:employer_id => 5, :id => "new"} instead of going to your new_employer_vacancy route (because routes are first-come-first-serve).
To correct this, add a constraint to your first route to ensure that only numbers (and not the string "new") is accepted into the employer_vacancy route:
get '/employers/:employer_id/vacancies/:id',
to: 'vacancies#show_specific_emplyer_vacancies',
as: 'employer_vacancy',
constraints: { id: /\d+/ } # <- This line

As Wes Foster said rails router is trying to find a first match.
It means that given a path /employers/999/vacancies/new your router looks through the routes and when it sees get '/employers/:employer_id/vacancies/:id he thinks that this route matches. So :employer_id is 999 and :id is new.
I'd suggest to put the route with :id at the end of employers routes:
...
get '/employers/:employer_id/vacancies/new'
...
get '/employers/:employer_id/vacancies/:id'
Btw this is better than adding a constraint because:
It is easier
It doesn't pollute routes file
Later you may want to change ids to be hashed or alphabetic and then you'd have to change the constraint

Related

rails named route puts '.' instead of '/' in URL on updating [duplicate]

This question already has an answer here:
Rails dot instead of slash in URL
(1 answer)
Closed 5 years ago.
Update #3 ... fixed! Solution was moving the new name space code (get 'dash', to: 'dashes#show') to the bottom of the routes.rb file just above the root "campaigns#index" entry.
Update #2 ... it's not a pluralization as it's called singularly, shown below & removing the named route automatically corrects all issues.
Update #1 ... found reason why no one had listed period in place of slash in URL ... it's unix nouns, not english ... IE: if you search for 'dot' in place of '.', then you get all sorts of answers.
I'm flumoxed by this one ... made my first named route the other day, everything looked great until suddenly it appears that the edit page when called from the named route doesn't update properly, with error ...
No route matches [PATCH] "/dash.6"
Removal of the named route takes me back to normal routes & all options working. I can't find a mention of routing which uses '.' instead of '\', so I'm lost. My route file below & then the route results from rails server ...
Rails.application.routes.draw do
devise_for :users, controllers: { sessions: 'users/registrations' }
# map.login '/login', :controller => 'sessions', :action => 'new' ## 3rd try
# get '/dash', :controller => 'dashes', :action => 'show' ## 2nd try
# get 'dash', to: 'dashes#show' ## Original named route
resources :dashes
resources :campaigns
resources :players
resources :countries
root "campaigns#index"
# yank later
resources :neighborhoods
end
Rails results on server ...
Paths Matching (dashes):
dashes_path GET /dashes(.:format)
dashes#index
POST /dashes(.:format)
dashes#create
Paths Containing (dashes):
dashes_path GET /dashes(.:format)
dashes#index
POST /dashes(.:format)
dashes#create
new_dash_path GET /dashes/new(.:format)
dashes#new
edit_dash_path GET /dashes/:id/edit(.:format)
dashes#edit
GET /dashes/:id(.:format)
dashes#show
PATCH /dashes/:id(.:format)
dashes#update
PUT /dashes/:id(.:format)
dashes#update
DELETE /dashes/:id(.:format)
dashes#destroy
My form is standard rails generated & works whenever I remove the named route ... edit.html.haml renders the _form partial ...
%h1 Editing dash
= render 'form'
= link_to 'Show', #dash
\|
= link_to 'Back', dashes_path
_form.html.haml
= simple_form_for(#dash) do |f|
= f.error_notification
.form-inputs
= f.input :name
= f.association :user
= f.association :dashcampaigns
= f.association :dashplayers
.form-actions
= f.button :submit
As described in this question, typically the issue is when you confuse between collection (plural) and member (singular) controller actions.
A collection controller action is an action that does not have an ID since it does not manipulate an existing resource (dash) or since it works on a group of resources. The RESTful collection actions are: index, new, and create. Each of them has a helper method and a "verb" (method):
index: url: dashes_path, method: :get (method get is default)
create: url: dashes_path, method: :post
new: url: new_dash_path, method: :get
Note how both index and create share the same plural URL helper method dashes_path. Only the method option differentiates between them.
A member controller action is an action that has an ID of the resource it is manipulating (one particular dash). The RESTful collection actions are:
edit: url: edit_dash_path(#dash), method: :get
show: url: dash_path(#dash), method: :get
update: url: dash_path(#dash), method: :patch
destroy: url: dash_path(#dash), method: :destroy
See how except edit, all other actions use the same singular URL helper method dash_path(#dash).
You can find further details on this in the guides.
Now, the "dot instead of slash" symptom is when you mistakenly try to point to a member action in a way that should be used for collection actions. So if you try to do dashes_path(#dash) - there is no such thing. The only parameter dashes_path accepts is format, which is added to the URL in the end after a dot, that's why you're seeing a weird URL such as /dash.6.
Rails form builder form_for and extensions such as simple_form_for need to decide whether to point the form action at the #create collection action (when rendering the #new collection action) or #update member action (when rendering the #edit member action). They do so "magically" by taking a look at the object you give them when you do simple_form_for(#dash). If #dash.new_object? is true, they point the form action to #create, if it's false they point it to #update.
In your case when you used it "out of the box" it was all good. It started acting up on you when you added this line to your routes.rb:
get 'dash', to: 'dashes#show'
By default show is a member action, not a collection action. It must receive an ID. I think that this is why Simple Form is acting up on you. Instead of that alias, try this one:
get 'dash/:id', to: 'dashes#show'
Let us know if this fixes the issue.
And in general, I recommend to "work with" the RESTful routing rather then "working against" them. It is very rare to need to add named routes in routes.rb. There are exceptions, but I don't think it is justified in your case to deviate from conventions and try to use dash/1 rather than dashes/1. "Working with" Rails will get you the productivity boost it is known for, not "working against" it by trying to force it for relatively small details like this one.

Routing in rails - When to route to a crud method and when to route with the given parameter

I am in need of a little help regarding routing in rails. Traditionally if I have a route in routes.rb
resources:categories
it will match www.website.com/categories/id were id is an integer. But what happens if I wanted to route to a specific user or category like so:
www.example.com/categories/apple
instead of the traditional:
www.example.com/categories/4
I currently have these two lines in my routes.rb
match 'categories/:name' => 'categories#show'
resources :categories
so www.example.com/categories/apple will route to the show method in the categories controller correctly.
but
What if I want to create a new category? Here's the problem
www.example.com/categories/new
will route to the show method, and will not route to the new method
I can place an if statement in the show method checking is params[:name] == new, but I feel that there must be a better way to solve this problem.
My end goal is to route based on the string of the category (apple) and not based on it's ID (4) but also be able to create, update, and destroy a category.
Any tips?
Thanks!
you can pass a name as a parameter, for example you can try
link_to category_path(category.name) instead of link_to category_path(category)
and it will go to categories#show in controller, the route will look like example.com/categories/categoryName, in the show action of your cateogries controller, params[:id] will have the name, you'll need something like
Category.find_by_name params[:id] instead of Category.find params[:id]
Hope this helps you.
As #pdoherty926 says in the comment, you could use FriendlyId. If you want to manage it manually, you don't have to overwrite the routes, just put the needed code in the :show action:
class CategoriesControllers < ...
...
def show
if /^\d+$/ =~ params[:id]
# ... normal workflow for integer id
elsif /soe_regexp_that_matches_names>/
# ... do your thing with names
else
raise 404
end
end
...
end
I think the most simple way to do this your way is to define a route before your
match 'categories/:name' => 'categories#show'
like this:
match 'categories/new' => 'categories#new'
match 'categories/:name' => 'categories#show'
the order matters.

Rails: Why am I getting "No route matches"?

Snippet from routes.rb:
resources :templates do
post :add_rates
resources :rates
delete :remove_rate
end
Now I try to use the "add_rates" path in my form.
Tried both:
<%= form_for(#template.template_id, :html => {:class=>"form-horizontal"},:url=> { :action=>:add_rates}) do |f| %>
and:
<%= form_tag(:template_add_rates) do %>
But I'm always getting: No route matches {:action=>"add_rates", :controller=>"templates"}
Any help would be appreciated.
You're doing it wrong:
form_for [#template, :add_rates], html: { class: "form-horizontal } do
or
form_for #template, url: template_add_rates_path(#template), html: {class: "form-horizontal" } do
The template, and its ID, and the action you want (add_rates) all have to be passed in as the same parameter. You can't give it the template ID as the first argument, and then try to tack additional URL parameters onto it. Additionally, in both cases, you're missing key parts of the URL. In the first one, you're just giving it an ID, and :add_rates; Rails can't take an arbitrary number and know that it's a template ID that you're giving it. In the second case, you're giving it :template_add_rates; how is Rails supposed to know which template you're trying to add rates to, without a template ID? You need to give it all three pieces of the route you're trying to match: /templates/:template_id/add_rates.
There are also a bunch of other weird issues/errors with the code you've posted:
#template.template_id should be #template.id, unless you've explicitly deviated from Rails' conventions, which you should almost never do.
Your routes are pretty weird. You shouldn't be adding a add_rate route, you should be using the routes provided by your nested resources :rates line.
Your routes should look like this:
resources :templates do
resources :rates
end
This gives you routes like POST /templates/:template_id/rates for creating rates (instead of your add_rate route), and DELETE /templates/:template_id/rates/:rate_id for deleting rates (instead of your remove_rate route).

Setting up a dynamic rails route

I have a controller and a view (ctrler)
controller
def index
...
end
def show
#text = params[:text]
end
end
View (show.html.erb)
<%=#text %>
routes.rb
resources :ctrler
match 'ctrler/:text' => 'ctrler#show'
If I fire the rails s server up and load up http://localhost:3000/ctrler/hiiiiiii I get nothing but if I load http://localhost:3000/ctrler?text=hiiiiii I get text!
Im still trying to get the hang of rails I'm used toPHP but can someone give me some guidance here am I on the right track or have I missed something out?
resources :ctrler
creates the following rule
match "ctrler/:id" => "ctrler#show"
This route conflicts with
match 'ctrler/:text' => 'ctrler#show'
In the event of a conflict, the rule that appears first takes precedence, so when you go to 'ctrlr/hiiiii', it is setting the id parameter to hiiiii, not the text parameter. Try to change routes.rb to
match 'ctrler/:text' => 'ctrler#show'
resources :ctrler
and see if that helps.

Set Up Route for Accessing Private S3 Content

I've been following
https://github.com/thoughtbot/paperclip/wiki/Restricting-Access-to-Objects-Stored-on-Amazon-S3
and
Rails 3, paperclip + S3 - Howto Store for an Instance and Protect Access to try and get Paperclip's expiring links to work. I believe most of what I'm running into is one of the routing variety.
In my pieces_controller I put a method in like this
def download
redirect_to #asset.asset.expiring_url(1000)
end
And then in my routes, I put this:
match "pieces/download"
Then in my view I have:
<%= link_to download_asset_path(piece)%>
It would seem to be far from working, and I'm not sure what is messed up. I know I'm getting routing errors for one, but it's also telling me that my download_asset_path is undefined, which is likely also routing related... I feel like I'm doing everything all wrong.
Tearing my hair out. Thanks!
Try modifying your routes file to:
match 'pieces/download' => 'pieces#download', :as => 'download_asset'
Your match needs to tell which controller#action to go to, and the as option will allow you to name the route download_asset_path.
If your pieces controller is for a Piece resource it could be cleaner like:
resources :pieces do
member do
get :download
end
end
But then you would want to change the link to:
link_to 'Link text', download_piece_path(piece)
For further reading: http://guides.rubyonrails.org/routing.html

Resources