Forum: Ruby on Rails Restul Controllers with multiple access points

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
181976602397443ce119909b9d82cae2?d=identicon&s=25 blinking bear (Guest)
on 2007-05-19 00:30
(Received via mailing list)
I'm trying to solve the same problem outlined in this blog post by Tore
Darell.  Basically, what's the best practice for having multiple access
points to a nested resource:

IE:
class User < ActiveRecord::Base
  has_many :posts
end

class Category < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
end

This blog points out one method but I feel like creating a ton of
different
controllers is the cleanest method, any other thoughts?

http://tore.darell.no/entries/2-cleaning-up-your-n...
E3e98bfa99e82ac8b0cb63660dc23b14?d=identicon&s=25 Geoff Buesing (Guest)
on 2007-05-20 19:15
(Received via mailing list)
I would say, as long as there's more similarities than differences in
the way you retrieve and present posts in the different contexts,
stick to doing it DRY, i.e. one controller and one set of views for
posts, and use private methods in the controller and helper methods in
the view to abstract away the complexity. For example, you could do
something like this in the controller:

class PostsController < ApplicationController
  before_filter :find_parent

  def index
    @posts = @parent ? @parent.posts.find(:all) : Post.find(:all)
  end

private
  def find_parent
    @parent =
      if params[:category_id]
        Category.find(params[:category_id])
      elsif params[:user_id]
        User.find(params[:user_id])
      end
  end
end
This topic is locked and can not be replied to.