I have the following routes:
resources :users do
# List reviews made by user
resources :reviews, :only => [ :index ]
end
resources :products do
# List reviews by product, and provide :product_id for creation
resources :reviews, :only => [ :index, :new, :create ]
end
# Other actions don't depend on other resources
resources :reviews, :except => [ :index, :new, :create ]
Everything looks right, except ReviewsController#index:
def index
if params[:user_id]
@reviews = Review.find_all_by_user_id params[:user_id]
else
@reviews = Review.find_all_by_product_id params[:product_id]
end
respond_with @reviews
end
I was wondering if there’s a standard solution to the problem above, or if there is a better way to do it.
What you have there is fine, but if you want you can use two different actions as well. This approach should allow you to more easily change the view later on, and is a bit safer.
It will also keep your controller code a little cleaner and less susceptible to odd queries like
/products/10/reviews?user_id=100which would result in the user’s reviews being shown instead of the product’s reviews.The other alternative is to use different controllers as well: