how does rails differentiate the method for the same url - ruby-on-rails

I am new in rails,and I create the first rails application (Blog) follow the guide at rails's docs step by step.
However when I run the application,I found something I can not understand.
http://localhost:3000/posts/2
With GET method,this will return the details of post whose id is 2.
But when update this post,I found the action of the form is '/posts/2'.
When delete the post,I found rails create a form element in the body with action '/posts/2' and method POST,so I wonder how does rails know update or delete this post?
Since I do not found any condition word in the post controller.
Anyone can tell me?

Which action is run is determined by a unique combination of the path and the verb
Do the command rake routes in your app folder, and you'll see a list of routes.
Paths, are the RESTful routes to your resources.
Verbs are GET POST DELETE, and PUT
I would also recommend the Rails Routing Guide as reading, which explains this in a lot more detail.
Here's sample output from rake routes from one of my apps:
path name|verb |path |action
============================================================================
alias_lists GET /alias_lists(.:format) alias_lists#index
POST /alias_lists(.:format) alias_lists#create
new_alias_list GET /alias_lists/new(.:format) alias_lists#new
edit_alias_list GET /alias_lists/:id/edit(.:format) alias_lists#edit
alias_list GET /alias_lists/:id(.:format) alias_lists#show
PUT /alias_lists/:id(.:format) alias_lists#update
DELETE /alias_lists/:id(.:format) alias_lists#destroy
Note that show, update and destroy all have the same path, but a different verb.
show's verb = GET
update's verb = PUT
destroy's verb = DELETE

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 redirect_to post

I saw an example in the book The Rails 3 Way that says
redirect_to post
Does this have some special meaning because of the post, or if it is just a poor choice for an example and the post is just a domain object and it's redirecting to the url for that object.
I would need to see the full example for a complete answer, but my guess is that the author just picked "Post" as the name of one of the models and didn't realize it might cause confusion to the reader with the POST action.
As part of the HTTP Protocol (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html), you actually can't redirect to a POST action. Or, more explicitly, whatever destination you are calling with a redirect needs to return with the GET method.
Hope that helps!
Look at Rails Routing Guide then it should be clear why that is ok.
Also if you want to see routes for your application run:
cd path/to/your/app
rake routes
This will list routes available in your app.
you need a Post resource and the corresponding routes in config/routes.rb
just do "rails g resource post title:string content:text" for example to generate one. the route in "redirect_to post" is handled dynamically. the instance of Post "post" is passed in as the argument to the redirect_to method, causing the page to redirect to the posts#show action and passing the :id of that instance of Post. it's "rails magic"

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

RoR Routes: Why does the app assume I want the show action with every URL?

So, I'm trying to access other actions in my controller, and it assums I want "show" every time, when I really just want... the action I just had in my URL.
this is in my routes:
map.resources :attachments
And when I do
domain/attachments/any_action?params
I get this error:
ActionController::UnknownAction (No action responded to show. Actions: {list of actions}
Using rails 2.3.8
I think I know what you are getting at.
Yes show is assumed for singular uses and index for plural.
This is a convention.
Much of the power / magic in rails comes from "convention over configuration" and this is one of them. Yes it could have been /attachment/show/ or /attachments/index but why not just eliminate the show and index if these are the most common and have them available as defaults and that is what rails does.
Now, as for actions not being available, lets look at that. First of all, right off the bat, please do a rake routes at the command line and see what you get. Also please indicate which actions you are trying. The restful setup "resources" will make 7 actions available:- index, show, new, create, edit, update and destroy, but not "any action"
The rule in Rails is first route matched, first route served.
Because you define a resource, it will consider everything like domain/attachments/whatever to be show action for the whatever stuff.
So two choices here:
define your other routes and declare them before the resource
nest your other routes inside the resource (I don't know how to do that in Rails 2.x)

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