Last Updated: September 09, 2019
·
2.744K
· javiercr

Controller filter for both nested and non-nested resources

If you need something like this in your Rails app:

resources :users do
  resources :posts
end

resources:posts

You can keep your PostsController DRY with this simple filter:

before_filter :load_user

def load_user
  @user = User.find(params[:user_id]) if params[:user_id]
  @posts = @user ? @user.posts : Post.scoped
end

Then you can rewrite your CRUD actions like:

def new
  @post = @posts.build
end

def create
  @post = @posts.build(params[:post])
end

def show
  @post = @posts.find(params[:id])
end

def edit
  @post = @posts.find(params[:id])
end

def update
  @post = @posts.find(params[:id])
end

def destroy
  @post = @posts.find(params[:id])
end

Source: Stackoverflow

1 Response
Add your response

Clean, neat... Thanks, Javier

over 1 year ago ·