Routes causing legacy issues rails 5, cannot destroy etc - ruby-on-rails

This is a continuation of my previous question: Put or patch for new update action Rails
The solution to this question worked, however, the solution is causing other issues within the legacy system, I'll show the main two issues but I'm not sure how to go about making the system work peacefully until I can go about refactoring the system.
With post :update in place the following actions break, destroying anything, importing records, if I uncomment post :update then importing works, edit does not.
None of the forms are setup to use REST, which I can't change currently as I'm trying to handle the routes for now and then move onto the system itself.
Here is the example of a routes
resources :stock_groups, except: %i[destroy] do
member do
get :copy
post :copy
post :update # temp PATCH, PUT routes
end
collection do
get :list
get :import_stock_groups
get :download_stock_groups_template
post :preview_import_stock_groups
post :process_import_stock_groups
end
end
# remap wrong implmentation of paths
get '/stock_groups/edit/:id', to: redirect('/stock_groups/%{id}/edit')
get '/stock_groups/copy/:id', to: redirect('/stock_groups/%{id}/copy')
get '/stock_groups/show/:id', to: redirect('/stock_groups/%{id}')
Here is what I get when I go to import records
it's targeting the wrong method in the controller.
As for destroying this fails either, I did try adding something like post :destroy but this didn't work.
Any help would be great.

Well let us discuss error it is telling your exactly what is happening here. You are trying to searching StockGroup.find(params[:id]) which should be integer. As find will search your record by id value.
StockGroup.find(params[:id]) # only integer allowed
But in your request you are sending id = process_import_stock_groups which is not possible as rails convention you will have id integer unless you change it in model level by changing rails conventions.
So to test run rails c
StockGroup.find('process_import_stock_groups') # should not work but just try to know your error
Now which column you save this value in process_import_stock_groups so you method whould be
StockGroup.where(name_of_column: 'process_import_stock_groups').first
what you get? I hope it solve your issue.

Related

Understanding Rails singular and plural paths

I'm very new to using Rails and at the moment am building an Instagram clone as a project to help me understand Rails a bit better. I am following this very helpful tutorial on how to implement the likes/unlikes feature:
https://medium.com/full-taxx/how-to-add-likes-to-posts-in-rails-e81430101bc2
However, I don't fully understand the Rails paths - please could someone explain the difference between:
post_like_path and post_likes_path as mentioned in the tutorial. I cannot see why one is like and one is likes? :(
Really trying to get my head around this so would be so grateful for any insight!
Thanks :)
In Rails as per the REST -
If trying to refer to the single resource then use post_like_path.
If trying to refer to a collection of resources then use post_likes_path
When you want to show or delete a particular resource then you will have to provide an :id for the resource so that the target resource can be found.
[/posts/1/likes/1] - A single record of "like" is being referred here.
While in case of all records plural path is formed to refer to all like records -
[/posts/1/likes] - All records of "like" are being referred here.
post model can have multiple likes. But when we do undo like it will be singular right. so post_like_path will handle the single like and it's going to trigger "delete" action in controller.
post_likes_path will trigger the new action for for creating new like.
Please routes resources concept then you come to know more about it.
post_like_path is used for show page, update and destroy path. The post_likes_path will give you the path for the index and create actions.
This link is the ROR guide and has quite a simple explanation on it:
https://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use
I'd suggest to always run this command from terminal:
rake routes
Or just for LikesController:
rake routes -c likes
This shows all the routes related to likes controllers. That's the output, it tells a lot of things. You can see where the plural and singular is used.
# Prefix Verb URI Pattern Controller#Action
# post_likes GET /posts/:post_id/likes(.:format) likes#index
# POST /posts/:post_id/likes(.:format) likes#create
# new_post_like GET /posts/:post_id/likes/new(.:format) likes#new
# edit_post_like GET /posts/:post_id/likes/:id/edit(.:format) likes#edit
# post_like GET /posts/:post_id/likes/:id(.:format) likes#show
# PATCH /posts/:post_id/likes/:id(.:format) likes#update
# PUT /posts/:post_id/likes/:id(.:format) likes#update
# DELETE /posts/:post_id/likes/:id(.:format) likes#destroy
First column shows you the path, the second the pattern (with required parameters) and the third the controller with action (related to the view).
So, for example, take
# new_post_like GET /posts/:post_id/likes/new(.:format) likes#new
This says that the form for a new like can be placed to a page linked by this URL:
new_post_like_path(post_id: #post) note the parameter required. The page is views/likes/new.html.erb.
the controller is LikesController and the action is def new; end where you need to instantiate the objects to be used in that page: #like = Like.new and #post = Post.find(params[:post_id]).
The form is then submitted by POST action, so the line to check is the following:
# post_likes POST /posts/:post_id/likes(.:format) likes#create
As before, the page where the form is located is views/likes/new.html.erb, the url to submit the form is post_likes_path(post.id). The POST action when submitting the form is processed by the controller LikesController and the action is def create; end
Other example:
# post_like GET /posts/:post_id/likes/:id(.:format) likes#show
It tells that to show the Like object with a certain id, you need to visit this link_to: post_like_path(post.id, like.id), the controller is LikesController, the action is def show; end and the view is in views/likes/show.html.erb.
And so on..

Rails routing issue, can't figure out the link path

Let me fair from the outset, and tell you that I've 'solved' the problem I'm describing. But a solution that you don't understand is not really a solution, now is it?
I have a resource, Newsbites. I have an index page for Newsbites. All my CRUD actions work fine.
I created a separate index (frontindex.html.erb) that acts as the front page of my website to show the newest Newsbites. The formatting is different from my normal index so readers get a larger photo, more of the text of the article(more ads too:).
In my routing table, I have the following statements:
resources :newsbites
get 'newsbites/frontindex'
root 'newsbites#frontindex'
Rake routes show the following:
newsbites_frontindex GET /newsbites/frontindex(.:format) newsbites#frontindex
If I load my website from the root (localhost:3000), it works great. There is a separate menu page that is rendered at the top, and it loads fine. I can click on all links, except the 'Home' link, and they work fine.
The 'Home' link is:
<%= link_to 'Home', newsbites_frontindex_path %>
When I click on the linked, I get the following error:
Couldn't find Newsbite with 'id'=frontindex
The error points to the 'show' action of my Newbites controller. Here are the frontindex and show def from the controller. They appear exactly as I'm posting them:
def frontindex
#newsbites = Newsbite.all
end
def show
#newsbite = Newsbite.find(params[:id])
end
I don't get it. Why is the show action being called by newbites_frontindex_path when there is both a def and views that match? Now, I can get around this by simply pointing home to root_path. But that doesn't help me understand. What if this was not the root of the site?
Any help would be greatly appreciated.
Actually I'm very surprised your code worked at all. A route must define two things
Some sort of regex against which the URL of the user is matched (newsbites/frontindex is different than newsbites/backindex)
What do you want to do for a given URL ? You want to point to a controller action
Rails won't usually "guess" what that action is. Or maybe, he was still able to "guess" that you wanted to use the newsbites controller, but it didn't guess the action right this time :(.
You should declare the root like this, which is what you did
root 'controller#action'
For the rest, there are two ways you can declare it. I prefer the second one
resources :newsbites
get 'newsbites/frontindex', to: 'newsbites#frontindex'
resources :newsbites do
# stuff added here will have the context of the `newsbites` controller already
get 'frontindex', on: :collection # the name of the action is inferred to be `frontindex`
end
The on: :collection, means that 'frontindex' is an action that concerns ALL the newsbites, so the URL generated will be newsbites/frontindex.
On the other hand get 'custom_action', on: :member, means that the custom_action targets a specific item, the URL generated would look like newsbites/:id/custom_action
EDIT : Rails also generate path_helpers based on the route declaration
get 'test', to: 'newsbites#frontindex'
get 'test/something', to: 'newsbites#frontindex'
resources :newsbites do
get 'frontindex', on: :collection
get 'custom_action', on: :member
Will generate path helpers
test_path
test_something_path
# CRUD helpers : new/edit/show/delete, etc. helpers
frontindex_newsbites_path
custom_actions_newsbite_path(ID) # without s !
You can always override this by adding an as: option
get 'custom_action', on: :member, as: 'something_cool'
# => something_cool_newsbites_path
Rails routes thinks that frontindex is an id. That's what the error message says. So it goes to GET newsbite/:id which maps to show.
You need to find a way let Rails routes know that frontindex is not an id.
On a side note: The order in which you define routes matters. The first one matched will be used. If you have GET newsbite/:id and GET newsbite/frontindex then the one that appears first will be matched. In your case this is the first one.
Maybe try to change the order.

Strange Rails resource routes behavior

I've met strange error. Im not sure this is bug. However i never met this strange behavior before.
resource :watches
Makes such strange routing table:
watches POST /watches(.:format) watches#create
new_watches GET /watches/new(.:format) watches#new
edit_watches GET /watches/edit(.:format) watches#edit
GET /watches(.:format) watches#show
PUT /watches(.:format) watches#update
DELETE /watches(.:format) watches#destroy
As you see no ID param and messed actions
On same time:
resources :mibs
Make proper routes
mibs GET /mibs(.:format) mibs#index
POST /mibs(.:format) mibs#create
new_mib GET /mibs/new(.:format) mibs#new
edit_mib GET /mibs/:id/edit(.:format) mibs#edit
mib GET /mibs/:id(.:format) mibs#show
PUT /mibs/:id(.:format) mibs#update
DELETE /mibs/:id(.:format) mibs#destroy
I thought that is could be somehow inflector problem, but trying using "rockets" instead of "watches" give same result:
rockets POST /rockets(.:format) rockets#create
new_rockets GET /rockets/new(.:format) rockets#new
edit_rockets GET /rockets/edit(.:format) rockets#edit
GET /rockets(.:format) rockets#show
PUT /rockets(.:format) rockets#update
DELETE /rockets(.:format) rockets#destroy
Anything except my first two resources (servers and mibs) make such result.
Probably corrupted routing cache somewhere?
resource indicates a singleton resource: in other words, you're telling Rails that there's only ever one watch for each user, so passing IDs would be useless.
resources is the standard invocation for getting routes with IDs attached.
So, essentially, the problem is an inflector one, but for resource or resources, not for the name of your routes. For more information, check out the Ruby on Rails routing guide. It does a good job explaining the difference between singleton resources and the more usual kind.

rails_3_question :as => why is my /posts/new routing to posts/show after setting up a slug

I'm using Rails 3 and after setting up slugs, I found that posts/new no longer works.
posts/:id, posts/:id/edit and all the other CRUD operations work.
However /posts/new gives me a routing error
No route matches {:action=>"show", :controller=>"posts"}
Now for some reason posts/new is routing to posts#show. In my routes, its just
resources :posts
My theory is that since /posts/:slug now matches against things other than numbers ids, the show verb is being routed to first. However it doesn't make sense since posts/grr a nonexistent entry gives a different error than posts/new and posts/first comes out just fine with all its associated paths working fine as well.
Anyone know what might be going on?
I've uploaded the repo to https://github.com/cultofmetatron/cassowary/tree/photogallary
I know my code sucks, I'm still learning the ins and outs of the system and I'd appreciate any insight into whats going on.
In your comment the first part seems fine: add a column to the Post column called slug and so on, and the contents of that will become some or all of the URL used to display a specific post. (I'll assume the other CRUD operations should work as normal)
To find the URL, the router has to know how to know which controller and action will handle this URL (as compared to others). A normal resources :posts route will match all of the RESTful methods, e.g. mapping a GET request onto a path starting with the controller name, and if an id is specified (/posts/1) map to the posts#show controller method, if not, it will map to posts#index method. If the request is a PUT, or DELETE or POST, different actions around a standardized URL format will occur.
Two changes are needed:
URL with the post slug format needs to map to the posts#show method (which is modified accordingly), and
Any links to the show page that are generated on your site need to use the post slug instead of the id
I'll assume you're OK with URLs start with /posts (if not, you'll need to identify some other unique pattern).
The first change requires that you override the specific case of the show method using route globbing, my adding something like match 'posts/*slug before the standard resource route. Here's a link to the guide on route globbing: http://guides.rubyonrails.org/routing.html#route-globbing
The next change, modify the existing posts#show method so that it looks for slug instead of id, e.g.
def show
#post = Post.where("slug = ?", params[:slug])
...
end
Finally, change the way Rails handles the URL helper posts_path. Do this by overriding to_param in your Post model, e.g.
def to_param
"/posts/#{slug}"
end
And then you're done. Maybe.
After that, see how the friendly_id gem does the same thing :-) https://github.com/norman/friendly_id

Why is the scaffold generating routes like this? Why do they work?

The book "Agile development with Rails" shows in the second chapter, that you can say:
<%= link_to "Goodbye",say_goodbye_path %>
Instead of hardcoding the path to "/say/goodbye". Makes sense, I thought to myself. Probably Ruby is splitting the say_goodbye_path by _, assigns the first part as the controller name, the second part as the action name. But, afterwards, I generated the following scaffold:
rails generate scaffold User name:string mail:string
And I noticed in the index.html.erb view, that it had methods like: edit_user_path(user). I tried to rewrite it to user_edit_path(user), but of course, it didn't work. My question is, why are the scaffold links the other way around? How would I know if I should write them in the way the author uses them in link_to, or in the way they are generated by the scaffold. Can you shed some light on this?
The helper functions like user_edit_path are automatically generated by rails to map operations on resources to the matching routes and thus HTTP paths and HTTP verbs. You have to understand that you are dealing with resources here, not necessarily with simple controllers.
While most of the time your resources can map to a single controller, it doesn't have to be that way. You can have nested or combined resources which can result in rather complex routing definitions.
Resources are typically defined by giving it a name (userin this case) and defining some allowed operations on them. Rails encourages to follow the REST pattern there, so you can have shortcuts to have some operations pre-defined. One of them is edit, which by default matches to a GET request to users_controller#edit. Default operations on RAILS resources are:
HTTP verb path matching controller action
===================================================
GET /users #=> index
GET /users/1 #=> show
GET /users/new #=> new
GET /users/1/edit #=> edit
PUT /users/1 #=> update
POST /users #=> create
DELETE /users/1 #=> destroy
These mappings can be customized on your routes.rb (changing methods, adding or removing operations, ...) Generally you are encouraged to use the default mappings as these are supported by standard helpers and make your app easier to understand.
Scaffolds are code generated by a template which is not related to the routing.
Routing is based on the route.rb in your config folder. All resources are routed by default (when generated by scaffolds) but there's a default rule /:controller/:action/:id that you can enable. Think of a "catch all" case.
One way to see what routes to have is to edit route.rb and run rake routes and see how they change. There's an official guide here too: http://guides.rubyonrails.org/routing.html

Resources