开发者

The right way to organize controllers with nested resources (rails)

开发者 https://www.devze.com 2023-04-10 01:54 出处:网络
I\'m hoping this question isn\'t too subjective, but here goes. For simplicity sake, I\'ve got a User model with many nested resources. For instance, a @user has many @books, @cars, @friends.

I'm hoping this question isn't too subjective, but here goes.

For simplicity sake, I've got a User model with many nested resources. For instance, a @user has many @books, @cars, @friends.

In the user's "show" view, I present the user with a dashboard, that shows widgets for all of their things (books, cars, and friends).

My issue now is that the UsersController has to do any/all logic pertaining to books, cars, and friend开发者_JS百科s. And putting logic for Books, etc in the UsersController just feels wrong.


In rails you can use nested resources in your routes like so

resources :users do
  resources :books
end

That would give you something like

/users/id_of_user/books

Which would hit the index of your books controller, simply check for user_id availability inside your books controller and fetch all books attached to the current user if its there.

Using your controllers and routing this way you can easily spread your logic around to better suited controllers and keep it out of your users controller.

Check out the docs below for more information like snazy helpers for your new nested paths. http://guides.rubyonrails.org/routing.html#nested-resources


Shortly after commenting I found the :before_filter on the Rails guide. Using this, you can call actions based on whether the nested resource is found, and the related template. This is what I did, and works well for me!

   before_filter :user_resource

      def user_resource
        return unless params[:user_id]
        redirect_to root_url and return unless params[:user_id] == current_user.id.to_s
        action = :"user_#{params[:action]}"
        if self.methods.include? action
          self.send action
          render action
        end
      end

and an example of a method it calls

  def user_index
    ads = Classified.where(:owner_id => params[:user_id])
    @classifieds = ads
  end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号