I have a resource Library and a resource Books. A library can have lots of books, obviously. Something like Library.first.books works perfectly.
In my routes.rb file I've got:
resources :libraries
resources :books
What I'd really like to be able to do is request something like /library/3/books and get all of the books in the library with an id of three. I tried this:
resources :libraries, :shallow => true do
resources :books
end
resources :books
But when I request /library/3/books I get all of the books, not just library three's books. Is there a built-in/easy way to make this happen?
/library goes to index
/library/3 goes to show
/library/3/books goes to books with params[:id] = 3. You must render #books = Library.find(3).books.
I suggest you to build another model as a relationship model.
then use :
has_many :book, through: :somemodel
it works like tagging http://railscasts.com/episodes/382-tagging
In this way you do not need to worry about the nested routes.
Related
So this may be more of a convention question, but im writing a todo app to learn how to use rails as an API (Im somewhat intermediate with using rails normally) but this time im using it with React for the front end.
Im making a simple todo app, two models in particular being "Lists" and "ListItems". Lists has_many ListItems of course, and a ListItem belongs_to a List.
So naturally I have the routes set up like so:
resources :lists do
resources :list_items
end
Giving me routes similar to: /api/v1/lists/:list_id/list_items etc.., However I saw some people doing a similar app set it up like:
namespace :v1 do
resources :list_items
resources :lists
end
Which confuses me because how would you handle passing the actual "List" params to the route, when the route itself would not have a List_id param?
Or would this more be used for a join table somehow..but you would still have to populate the List_id regardless when creating a list_item for a specific list correct?
Is there a preferred way of doing this as far as routing goes? (And I suppose creating tables?) Since a has_many_through seems not really necessary in this case?
Unless there is more to the story, you are doing it the more conventional way. I suggest your can safely disregard that not-nested approach. The only enhancement I suggest is using shallow: true, like:
namespace :api do
namespace :v1 do
resources :lists do
resources :list_items, shallow: true
end
end
end
You can read more about shallow nesting in the guide.
I have 3 resources.
Projects
Books
Chapters
Projects and Books are many_to_many through ProjectBooks, Books have_many Chapters, which belong_to Books.
I easily can set up basic routes for /projects/1 and /books/2 and /chapters/3.
How do I list just the Books that are attached to a given project? How do I add information about those Books that is relevant to that Project?
Thus, my routes should be:
/books/2 - show book 2
/projects/1 - show project 1
/projects/1/books - list books in project 1 and additional information
/projects/1/books/2/chapters - information about chapters in book 2 relevant to project 1
My original thought was custom routes with a books method on my ProjectsController. Routing:
resources :projects do
get :books, on: :member
end
But that doesn't let me get /projects/1/books/2/chapters.
Then I thought about embedded resources:
resources :projects, param: :name do
resources :books do
resources :chapters
end
end
Which works, but instead of calling projects#books it calls books#index, which really lists all of the books, and gives me no way to get #chapters in the context of a project.
How do I handle the twin challenges of:
Books can be listed independently but also in the context of a Project
Adding specific information when listed in the context of a Project
EDIT:
My assumption is that only ProjectsController can discover which Books are part of this project, and certainly only ProjectsController knows how to add Project-specific data like statistics. If my assumptions are off and there is a different way to structure this, all for it.
Here's an idea:
You can do something like
match '/books/:book_id/chapters' => 'projects#chapters'
for your first approach (having everything in one ProjectController)
More info is in the Rails Guide on Routing.
EDIT (by OP):
I used your answer and did a slight variant:
resources :projects do
member do
get 'books', to: 'projects#books'
get 'books/:book_id/chapters', to: 'projects#chapters'
get 'books/:book_id/chapters/:chapter_id/units', to: 'projects#units'
end
end
Putting it inside of the :projects resources made it easier to manage.
The Application Concept:
I'm building a Ruby on Rails [3.2] application at the moment, which consists of 2 very basic controllers - accounts for the user authentication, and messages which belong to the accounts.
# app/models/account.rb
class Account < ActiveRecord::Base
has_many :messages
end
# app/models/message.rb
class Message < ActiveRecord::Base
belongs_to :accounts
end
I then, of coarse, setup my routes.rb to allow users to view their messages nested under accounts:
# config/routes.rb
resources :accounts do
resources :messages
end
The Question:
I want users to access their accounts without using an ID parameter in the URL like this: example.com/accounts/, which works perfectly fine.
Whenever I try and go to: example.com/accounts/messages however, rails treats "messages" as a parameter for the accounts_controller! The only way I can access messages now is by going: /accounts/5236/messages - which is NOT what I want.
My question is, is there a way to block/mask rails from checking parameters on my accounts controller so that I can access my messages like the example above? I'm really puzzled on this one, so please share your thoughts and ideas!
Your defined routes
resources :accounts do
resources :messages
end
implies you can only have URL like this :
/accounts/
/accounts/:id
/accounts/:id/:action
/accounts/:id/messages/
/accounts/:id/messages/:id
/accounts/:id/messages/:id/:action
If you want specify the URL /accounts/messages/, you must specify it in the routes
resources :accounts, :collection => { :messages => :get } do
resource :messages
end
Just to add some closure to this question, I've decided to go with this solution in my routes.rb file:
get "/accounts/messages" => "messages#index", :as => :message
This works well, but the only downside is that it has to be manually added each time if you add controlers under the accounts namespace down the track. Oh well.
ForgetTheNorm also has a fantastic alternate solution below, so give that a shot if this doesn't work for you!
Okay, so here's an example scenario. There is a student resource resources :students, and students has and belongs to many collections: resources :clubs, resources :majors, etc.
So we can set up our routes easily enough...
resources :clubs do
resources :students
end
resources :majors do
resources :students
end
resources :students do
resources :clubs
resources :majors
end
which generates us a bunch of standard RESTful routes
/clubs
/clubs/:id
/clubs/:club_id/students
/clubs/:club_id/students/:id
/majors
/majors/:id
/majors/:major_id/students
/majors/:major_id/students/:id
/students
/students/:id
/students/:student_id/clubs
/students/:student_id/clubs/:id
/students/:student_id/majors
/students/:student_id/majors/:id
So here's my question. With REST semantics, how would one delete a major for a student?
Browsing students under a major /majors/:major_id/students/:id would show that student in the specific major's 'collection'. But the route for deleting an :id, points to StudentsController#destroy, which would delete the student completely. Whoops! So maybe we go the other way, and perform DELETE on the resource at /students/:student_id/majors/:id and well now UnderwaterBasketweaving is now no longer offered at this school...Whoops!
Now granted, we could set the destroy method of ClubsController, MajorsController, or StudentsController to look for club_id, or major_id, or student_id, but lets say we also down the road want to add Fraternities and GraduatingClasses, etc. Each class would start to be comprised of huge switch conditionals looking to see what param was present... and then find the collection of either the top resource and remove the bottom resource, or vise versa. The Models themselves should decide whether they delete themselves if they have no more association records... 'Destroy' on that resource has become really a misnomer...
Is there an easier way to do this? Even popular restful rails plugins like make_resourceful or resource_controller would blow away UnderwaterBasketweaving when removing it from Joe's Majors or completely delete JohnDoe when removing him from the major UnderwaterBasketweaving. It would seem there's a potential for looking at the association to understand the desired effects of the semantics and what 'destroy' should do.
Then again, am I looking at this all wrong? Is it not UnderwaterBasketweaving -> Joe but UnderwaterBasketweaving+Joe as a single resource and what we're deleting is truly not Joe, nor UnderwaterBasketweaving, but the resource representing the combination? However, that's not easy when the controllers are Students and Majors, that in effect represent resources of the same name (MVC has really become RV...in the 'convention' approach and not developing Controllers that may have no bearing on a Model name, or the path to reach it) So you'd be deleting a Major or a Student; pick your poison...
How can I avoid managing conditionals across an infinite graph of associated resources where delete really isn't the intent when the delete is desired to be in context of a collection and not pertaining to its singularity...?
...major.student.delete... Is there a way for 'student' ActiveRecord object to know it was sent a 'delete' message in a method chain beginning with the 'major' AR object ?
Well the standard RESTful aproach is to use has_many :through and generate a cotroller for the association resource. Naming association resources is always difficult, but I'll attempt for this example.
resources :majors do
resources :studies
resources :students
end
resources :students do
resources :studies
resources :majors
end
The models would be of course:
class Major < ActiverRecord::Base
has_many :studies
has_many :students, :through => :studies
end
etc. (comment if you want me to elaborate)
Then for a student you wouldn't DELETE it's associated #student.major but his #student.studies.where :major => #major.
This might be a tough one
I have a site which is using a polymorphic comments model.
Lets say the first model is library, and the second is book
so we have, library/1/book/63/
how do I route it so comments are then library/1/book/63/comments/1 ?
Thanks,
Elliot
update: looking for code for routes.rb file
You just nest them:
map.resources :libraries do |library|
library.resources :books do |book|
book.resources :comments
end
end
It may be confusing, but the polymorphic aspect of the data model is independent of the routes.
To call them via named routes, for a comment you'll need to provide a library and a book, even if it's unambiguous.
map.resources :libraries do |library|
library.resources :books, :has_many=>[:comments]
end