Rails nested resources and routing - how to break up controllers? - ruby-on-rails-3

I have the following models:
Post
Tag
TaggedPost (from which Post and Tag derive their associations by has_many :through)
And I have the following routes.rb file:
resources :tags
resources :posts do
resources :tags
end
So when I navigate to, say, /posts/4/tags, that will shoot me into the index action for the Tag controller with the post_id value set in the parameters array. Cool.
My question is though, now that I'm accessing the nested tags resource under posts, should I be hitting the Tags controller still? Or should I setup some other controller to handle the nested nature of tags at this point? Otherwise I have to build additional logic into the Tags controller. This can be done of course, but is this the common way of handling nested routes and resources? The code I have in the index action for the Tags controller is as follows:
TagsController.rb
def index
if params[:post_id] && #post = Post.find_by_id(params[:post_id])
#tags = Post.find_by_id(params[:post_id]).tags
else
#tags = Tag.order(:name)
end
respond_to do |format|
format.html
format.json {render json: #tags.tokens(params[:q]) }
end
end
I can see the code in this controller growing increasingly large, as I plan for many additional resources to be associated with tag resources. Thoughts on how to break this out?
Summary of questions:
If a resource is nested, should the nested resource be going through a different controller representing the nested nature of the resource? This is opposed to going through the normal controller as I am in the code example that I provided.
If so, how should these controllers be named and setup?
Let me know if you need more information.

I think the best solution is to split up controllers:
resources :tags
resources :posts do
resources :tags, controller: 'post_tags'
end
And then you have 3 controllers. Optionally, you can inherit
PostTagsController from TagsController to do something like:
class PostTagsController < TagsController
def index
#tags = Post.find(params[:post_id]).tags
super
end
end
If the difference is only the retrieval of tags, you can:
class TagsController < ApplicationController
def tags
Tag.all
end
def tag
tags.find params[:id]
end
def index
#tags = tags
# ...
end
# ...
end
class PostTagsController < TagsController
def tags
Product.find(params[:product_id]).tags
end
end
Use that methods and simply override tags in the inheriting controllers ;)

All you are doing with nested resources is changing the routing URL. Only thing you would have to do is make sure you are passing the proper id (in your case post)to the tag controller. Most common error is the Can't Find *** ID.
If you don't nest a profile route into a user route it would look like this
domain.com/user/1
domain.com/profile/2
When you nest the routes it would be
domain.com/user/1/profile/2
That is all that it is doing and nothing else. You don't need additional controllers. Doing nested routing is just for looks. allowing your user to follow the association. The most important thing about nesting routes is that you make sure you make the link_to's to the right path.
When not nested: it would be
user_path
and
profile_path
when it is nested you would need to use
user_profile_path
rake routes is your friend to find out how the routes have changed.
Hope it helps.

Related

How do I create routes for a controller that does nothing with models in Rails?

Still pretty new to Rails, so if I'm taking the completely wrong approach, please feel free to straiten me out.
How do I make routes.rb aware that there's a root controller full of actions that don't manipulate models, while preserving the route helper methods? I'd like it to respond to requests like these:
http://localhost/download
http://localhost/share
With route helpers like
download_app_path
share_path
but without static named routes like these:
match '/download' => 'site#download', :as => :download_app
match '/share' => 'site#share', :as => :share
from a SiteController that doesn't create, show, or otherwise manipulates models from my app.
I've tried using an approach like this, but it works without generating the route helpers ( naturally )
match '/:action', :controller => 'site'
I could theoretically do without the route helpers, but I think they're a bit easier to read than passing hashes of url options to link_to or form methods.
Is there a way to accomplish a more resourceful root controller, or is what I'm trying to do unconventional for Rails?
Edit
For clarity, here's what this SiteController class looks like:
class SiteController < ApplicationController
def download
#custom_options = { .. }
end
def share
#custom_options = { .. }
end
def about
end
end
Its purpose is to allow me to collect pages that don't interact with resources ( such as Users or Friendships ) into a single controller and maintain them all in one place. I'm trying to set this controller up as the application root controller - so all paths from this controller will be directly off the app host ( myapp.com/download )
Thanks in advance!
routes and resources are not tied to models. it's just a RESTful convention. if you just want to use the index actions, in your example download and share could be done like
resouce :download, only: [:index]
resouce :share, only: [:index]
see all the examples in the guides http://guides.rubyonrails.org/routing.html
if you want to add the download and share functionality to some "resource" like, say a picture, then you would do something like:
resources :pictures do
get 'download', :on => :member
get 'share', :on => :member
end
a resource always has and endpoint /pictures for example. so if you want to have paths directly to your host, then you need to provide custom matchers in your routes like you did in your examples.

REST Routes and overriding :id with to_param

My controller is using the default RESTful routes for creating, adding, editing etc
I want to change the default :id to use :guuid. So what I did was:
# routes.rb
resources :posts
# Post Model
class Post < ActiveRecord::Base
def to_param # overridden
guuid
end
end
This works but my modifed REST controller code has something like this
def show
#post = Post.find_by_guuid(params[:id])
#title = "Review"
respond_to do |format|
format.html # show.html.erb
end
end
When I see this this code ..
Post.find_by_guuid(params[:id])
it would seem wrong but it works.
I don't understand why I can't write it out like this:
Post.find_by_guuid(params[:guuid])
Why do I still have to pass in the params[:id] when I'm not using it?
Looking for feedback on whether my approach is correct or anything else to consider.
Even though it works it doesn't always mean it's right.
Type rake routes in your console, and check the output of the routes. You'll see the fragment ':id' in some of them, that's where the params[:id] comes from. It's a rails convention : when you use resources in your routes, the parameter is named id. I don't know if you can change it (while keeping resources; otherwise you could just go with matching rules), but you shouldn't anyway : even if it seems not very logic, it actually has sense, once your understand how rails routing works.

Paginate on two collections on the same model

I am planning to add some pagination to a couple of models in my application and I feel like I am missing a key concept here. Here is my application:
class Gallery < ActiveRecord::Base
has_many :photos
has_many :comments
end
class GalleryController < ApplicationController
def show
# some process here
#gallery = Gallery.find(params[:id])
end
end
I would like to be able to paginate independently on both the photos and comments for the given gallery that I am displaying. I need this to be done with AJAX and I have a feeling that calling 'show' with a parameter for photos or gallery is overkill (ie. why would I need to find the gallery if I am only looking for photos or comments).
How should I design this feature?
What is the alternative to calling GalleryController.show here?
I'd set it up like this:
class GalleriesController < ApplicationController
def index
#galleries = Gallery.paginate(params)
end
end
class CommentsController < ApplicationController
def index
#comments = parent.comments.paginate(params)
end
def parent
#parent ||= Gallery.find(params[:gallery_id])
end
end
class PhotosController < ApplicationController
def index
#photos = parent.photos.paginate(params)
end
def parent
#parent ||= Gallery.find(params[:gallery_id])
end
end
# config/routes.rb
resources :galleries do
resources :photos
resources :comments
end
Then you just request:
/galleries/1/comments
/galleries/1/photos
Check out the inherited_resources gem for this nested model pattern.
But ideally you'd want to get this all in one request. Check out this post on the Presenter Pattern in Rails.
Hope that helps.
yes, i'd absolutely recommend using inherited_resources, as it saves you a lot of boilerplate code. just set up these resources as described by viatropos, add JSON-responder (with inherited_resources, its as easy as adding respond_to :json, :html to your controller). then on the ajax side use a tempting plugin, like jquery.tmpl or mustache.js or whatever, pre-render an item template for each resource, and then use ajax to retrieve your paginated data as JSON and render it into your templates. it's incredibly easy, but if you need a step by step howto, just ask.

Rails 3 - Nested resources and polymorphic paths: OK to two levels, but break at three

I'm trying to do a simple family reunion site with: "posts", "families", "kids", and "pictures". Ideally I'd like the routes/relationships to be structured this way:
resources :posts do
resources :pictures
end
resources :fams do
resources :pictures
resources :kids do
resources :pictures
end
end
In the models I have the necessary "belongs_to" and "has_many" relationships set between fams and kids. Fams, kids, and posts all are defined with "has_many :pictures, :as => :imageable" while pictures are defined as: belongs_to :imageable, :polymorphic => true
When trying to do link_to "Edit" and link_to "Destroy" in the pictures views I run into all sorts of _path problems. polymoric_path works fine at two levels, namely for posts-pictures and fams-pictures but it fails to handle the three level case of fams-kids-pictures. I'm guessing that it was not designed to handle the two levels of "imageable" objects above the picture object. Another issue is that in one instance the pictures controller has to handle a "one level" resource-nesting situation and in another it has to handle a "two levels" situation. Not sure how to approach this.
One thing I did try was to not nest resources more than one deep, per the Ruby Guides directions. I structured them like this:
resources :posts do
resources :pictures
end
resources :fams do
resources :pictures
resources :kids
end
resources :kids do
resources :pictures
end
This caused another set of problems with paths since the fam to kid relationship was no longer preserved. I also could not get polymorphic_path to function correctly accross all the different picture views.
So here is my main question: Does anyone know of a Rails 3 example/tutorial where nested resources, belongs-to/has_many, and polymorphic relationships are all put together, especially where it is not just the simple, two-level relationship that most examples show? (I'm fairly new to Rails and the Rails 2 examples I've found in these areas are confusing given my lack of Rails historical experience.)
Or can someone tell me how to structure the link_to EDIT and link_to DELETE statements for my picture views, as well as the redirect-to statement for my create, update, and destroy methods in my pictures controller?
Thanks!
Your code example that limited your nesting to 2 levels is quite near the answer. To avoid duplicate routes for fams->kids and kids, you can use the :only option with a blank array so that the 1st-level kids will not generate routes except in the context of kids->pictures, like so:
resources :posts do
resources :pictures
end
resources :fams do
resources :pictures
resources :kids
end
resources :kids, only: [] do # this will not generate kids routes
resources :pictures
end
For the above code, you can use the following to construct your polymorphic edit url:
polymorphic_url([fam, picture], action: :edit) # using Ruby 1.9 hash syntax
polymorphic_url([kid, picture], action: :edit)
Have been having this exact same problem for a while. I have it working now, but it isn't beautiful :S
From a nested monster like:
http://localhost:3000/destinations/3/accommodations/3/accommodation_facilities/52
Your params object ends up looking like this:
action: show
id: "52"
destination_id: "3"
accommodation_id: "3"
controller: accommodation_facilities
where "id" represents the current model id (last on the chain) and the other ones have model_name_id
To correctly render another nested link on this page, you need to pass in an array of objects that make up the full path, eg to link to a fictional FacilityType object you'd have to do:
<%= link_to "New", new_polymorphic_path([#destination, #accommodation, #accommodation_facility, :accommodation_facility_type]) %>
To generate this array from the params object, I use this code in application_helper.rb
def find_parent_models(current_model = nil)
parents = Array.new
params.each do |name, value|
if name =~ /(.+)_id$/
parents.push $1.classify.constantize.find(value)
end
end
parents.push current_model
parents
end
Then to automatically make the same link, you can merrily do:
<%= link_to "New", new_polymorphic_path(find_parent_models(#accommodation_facility).push(:accommodation_facility_type)) %>
Any pointers on making this solution less sketchy are very welcome :]
I can't speak for the polymorphic association problem (probably need more info on the actual error) but you are indeed headed in the right direction by defining your nested resources only one level deep. Here's a popular article by Jamis Buck that has become a reference and that you should probably check out.

Rails 3 route scoping and/or nesting

I am having trouble scoping routes that I don't want to nest.
I have the following routes:
resources :foos
resources :bars
resources :bazs do
resources :hellos
resources :worlds
end
The foo, bar, and baz models all belong_to a user model. I don't want to nest another layer, but I do want to have a prefix in my url that corresponds to a user's permalink attribute (similar to each github repo prefixed by a username). So I have a before filter on all of my controllers
def get_scope
#user = User.find_by_permalink(params[:permalink])
end
Modified to_param thanks to #cowboycoded
class User < ActiveRecord::Base
def to_param
permalink
end
end
I wrapped those routes with
scope ":permalink", :as => :user do
#nested routes here
end
Now everything works fine as long as I pass #user to every non-index route. It doesn't seem very dry to have to go back to all of my views and replace (#foo) with (#user, #foo) when it is already scoped.
Unless I am mistaken, the to_param method simply replaces :id so that urls such as /users/:id appear as users/permalink instead of users/1. I attempted to use this :id in my scope, but it conflicts with foo's :id param and breaks everything. Maybe there is a connection to paths that I am missing?
Thanks for any suggestions that you may have!
Have you tried using the to_param method in your model? This will allow you to override the default and use something other than id, and will work with the URL helpers
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-to_param
Example from documentation:
class User < ActiveRecord::Base
def to_param # overridden
name
end
end
user = User.find_by_name('Phusion')
user_path(user) # => "/users/Phusion"
I'm not sure how well this plays with scope, since I haven't tried it, but I guess its worth a shot.