Does every belongs_to has_many association need nested routes? - ruby-on-rails

This is a fairly basic question but I haven't been able to find concrete answers online. Every has_many belongs_to does not need nested routes correct? Should you only use nested routes when you're looking for URLs of the form class/:id/class/:id?
For example, let's say I have two classes Profile and Post.
models/profile
has_many :posts
models/post
belongs_to :profile
There's no separate post URL, the posts are displayed in profiles/show. Should the post routes (in this case it would be only actions like :new, :create, and :destroy) be nested inside the :profiles resource? The rails guide states that resources should not be nested more than one level deep and there are often times. Making nested resources for every association seems like it would violate this rule very quickly. Thanks in advance!

If you have no use for /profile/1/posts or /profile/1/posts/1 you do not need the nested routes. However, I urge you to rethink, nested routes make for clean RESTful APIs
For example, the neat little nested route:
resources :profile, :shallow => true do
resources :posts
end
will give you all these realy useful routes:
profile_posts GET /profile/:profile_id/posts(.:format) posts#index
POST /profile/:profile_id/posts(.:format) posts#create
new_profile_post GET /profile/:profile_id/posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
profile_index GET /profile(.:format) profile#index
POST /profile(.:format) profile#create
new_profile GET /profile/new(.:format) profile#new
edit_profile GET /profile/:id/edit(.:format) profile#edit
profile GET /profile/:id(.:format) profile#show
PUT /profile/:id(.:format) profile#update
DELETE /profile/:id(.:format) profile#destroy
This way you have to freedom to choose the nested route when necessary/useful, such as
GET /profile/:profile_id/posts/new(.:format) # create a new post for the given profile_id
GET /profile/:profile_id/posts(.:format) # return all posts for the given profile_id
and use the shallow routes where the nested routes are not necessary

If you read Section 2.7 of the Ruby on Rails Guide it states that:
Nested routes allow you to capture this relationship in your routing.
See - http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default for reference.
Further to this you may want to perform particular operations on a class i.e. user which has create, edit etc ... every user is associated with a particular booking. That means that whenever you do anything to a user, you really are doing something to an user/booking. Because this is associated with this.
RESTful routes is a clean way of setting your application and making good use of unified resource identifiers. An example of this would be identifying a particular user such as /users/1/bookings/3 this would show the first user.

Related

How to access URL in Rails Show action in Controller

This is the URL I want to access in my show method
http://localhost:3000/students.1
but the error is coming
ActiveRecord::RecordNotFound in StudentsController#show
Couldn't find Student with 'id'=
def show
#student = Student.find(params[:id])
end
my routes are
new_students GET /students/new(.:format) students#new
edit_students GET /students/edit(.:format) students#edit
students GET /students(.:format) students#show
PATCH /students(.:format) students#update
PUT /students(.:format) students#update
DELETE /students(.:format) students#destroy
POST /students(.:format) students#create
root GET / students#index
Can someone tell me how do I access that students.1 in my URL so that I can display that particular student on my show page ?
Thats the wrong path. It should be /students/1.
And your routes are wrong. You can tell that the routes are off by the lack of an id segment and the fact that it maps GET /students to the show action instead of the index.
# Wrong
resource :students
# Right
resources :students
Pluralization is extremely important in Rails and is worth paying careful attention to. While its just one tiny letter these methods produce completely different routes.
resource is for singular resources. This is not the case here.
there is some issue with your route formation
your url is not properly forming , try below
students_path(id: student.id)
It should be http://localhost:3000/students/1
Check out this docs

Rails custom routes with scopes

I have a scope 'games-posts' in my Post model that fetches posts that belong to a Topic with a title "Games" (Post belongs_to Topic). In my routes I have defined the route get 'games-posts', to: 'topics#games' and have the view where I show the list of those games posts. In each of the posts I have a link that takes me to that specific games post.
Apart from that I have regular resources :posts routes that the generate standard urls:
`/posts`
`/posts/:id`
`/posts/:id/edit`
etc.
My problem is that when I click on a specific post on games-posts page right now it redirects me to /posts/1 (for example).
It would be cool if it redirected me to /games-posts/1 instead of /posts/1 and similarily I would like to edit and destroy those posts from games-posts page. How can I accomplish this? Is it possible to define something like
resources :games-posts?
The :controller option lets you explicitly specify a controller to use for the resource. For example:
resources :games_posts, controller: 'posts'
Now run rake routes and you will get following output to verify if it generated your required paths.
games_posts GET /games_posts(.:format) posts#index
POST /games_posts(.:format) posts#create
new_games_post GET /games_posts/new(.:format) posts#new
edit_games_post GET /games_posts/:id/edit(.:format) posts#edit
games_post GET /games_posts/:id(.:format) posts#show
PATCH /games_posts/:id(.:format) posts#update
PUT /games_posts/:id(.:format) posts#update
DELETE /games_posts/:id(.:format) posts#destroy

Rails Multiple-User Blog Routing

I need a little bit of help on RESTful routing. Basically, im trying to recreate http://medium.com to help improve my skills in rails.
I have the registration done via Devise.
Im stuck at the actual blog routing. I want the routes to be something like this: domain.com/username/post-title. Im not sure if it is possible to make this kind of app follow the restful pattern.
How would I do it?
I was thinking of doing something like this:
scope module: :username do
resources :posts
end
but when I rake routes, I just get something weird:
posts GET /posts(.:format) username/posts#index
POST /posts(.:format) username/posts#create
new_post GET /posts/new(.:format) username/posts#new
edit_post GET /posts/:id/edit(.:format) username/posts#edit
post GET /posts/:id(.:format) username/posts#show
PATCH /posts/:id(.:format) username/posts#update
PUT /posts/:id(.:format) username/posts#update
DELETE /posts/:id(.:format) username/posts#destroy
root GET / home#index
The url for these routes still stay /posts and for some reason arent :username/posts.
I really dont know how to apprach this.
Thanks! :)
That is because you are using 'scope'. Try using 'namespace' instead if you want the module name in your url
namespace :username do
resources :posts
end

No route matches [GET] "/posts/new"

I am completely new to ruby, andI am following this ruby rails tutorial step by step, except for the detail that I've called my app "cinema".
I created a resource named "posts", there is a controller class called posts controller. From the page posts/new I should post a text with title, and execute an action (show). I am trying to add the show action in the routes file and in the controller class.
The show action should be called when a form is submitted, the form includes a title and a text field, mapped into the database.
In paragraph 5.7, there is a non-clear instruction: it says to add this line:
post GET /posts/:id(.:format) posts#show
To my routes.rb file, but it doesn't say where to write it exactly, I put it under resources:posts (maybe it's the wrong place, it doesn't saying anything about that).
I also added the show method to the controller class:
def show
#post = Post.find(params[:id])
end
private
def post_params
params.require(:post).permit(:title,:test);
end
But when I submit the form I still get this error:
The rake routes command result:
Prefix Verb URI Pattern Controller#Action
welcome_index GET /welcome/index(.:format) welcome#index
root GET / welcome#index
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
It doesn't tell you to add it to routes.rb. It's one of the routes that is created automatically with:
resources :posts
Remove the line from your routes.rb restart the server and continue with the tutorial.
Tip: you can run rake routes to see all available routes in your application.
Your whole question seems completely contradictory to me.
You never do this in rails routes -
post GET /posts/:id(.:format) posts#show
Instead in routes.rb file.
get 'posts/:id' => 'posts#show'
The routing is done on a priority basis (first come first serve), so if your are adding get 'posts/:id' after the resources :posts, it is of no use as resources :posts already does it for you (read the rails routing guide on resources).
Your form submission should be a post data, if you are using resources 'new' should be a 'get' data and the corresponding 'post' should be 'create'. Your 'new' route has an error, then where else are you rendering your form to submit the form data?
My suggestion is that you keep the 'resources :post' and remove every other this corresponding to your :post from routes file. If you have everything else right then it should probably work fine.
resources :posts
delete it
rails s
paste resources :posts
rails s
I make it and success

rails rake routes where are they from

When you type
rake routes
a bunch of routes come out, but where are they defined???
I know some are default, and how about the others?
For example, this is a script from a controller, I tried to take off the 's' from do_something, but can't make it work.... are they defined somewhere else too?
Also, when do they take parameters and when not, how I know it ? Thanks!
def hello
redirect_to do_things_shop_path(shop)
end
def do_things
end
Rails routing configurations are kept in config/routes.rb file.
Taking parameters depends on many things. rake routes will show with routes take parameters. Member actions will take parameters.
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
edit_post GET /posts/:id/edit(.:format) posts#edit
In the last line, you will url like posts/:id/edit. This path requires :id parameter. You can call this route many ways. One of them is like:
edit_post_path(#post)
If you want to create a custom action, (say under posts controller), you can declare it as follow:
match `/posts/:id/things_with_id`, :to => 'posts#do_things_with_id', :as => 'do_things_with_id
match `/posts/things_without_id`, :to => 'posts#do_things_without_id', :as => 'do_things_without_id
First one requires an ID while the second one does not. Call them accordingly:
do_things_with_id_path(#post)
do_things_without_id()
For a resource, you can create these easily using member & collection action. Member action needs id while collection action does not.
resources :posts do
member { get 'do_thing' }
collection { get do_things' }
end
hope you got it.
By the way, you must read the following guide if you want to understand these clearly.
http://guides.rubyonrails.org/routing.html

Resources