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
Written by Javier Cuevas
Related protips
1 Response
Clean, neat... Thanks, Javier
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#