Skip to content

Instantly share code, notes, and snippets.

@mrgenixus
Created March 17, 2014 04:30
Show Gist options
  • Select an option

  • Save mrgenixus/9593994 to your computer and use it in GitHub Desktop.

Select an option

Save mrgenixus/9593994 to your computer and use it in GitHub Desktop.
RESTful Polymorphic review creation methods for associated models
class ProductsController < ApplicationController
# [...] Product Crud
def create_review
@product = Product.find params[:id]
review = @product.reviews.new
review.user_id = current_user.id
review.subject = params[:subject].nil? ? "Untitled" : params[:subject];
review.body = params[:body]
respond_to do |format|
if review.save
update_popularity @product
format.html { redirect_to @product, notice: "added review" }
else
format.html { redirect_to @product, error: "Unable to review product, errors #{review.errors.full_messages }" }
end
end
end
private
def update_popularity
# => do the stuff
end
end
class ServicesController < ApplicationController
# [...] Service Crud
def create_review
@service = Service.find params[:id]
review = @service.reviews.new
review.user_id = current_user.id
review.subject = params[:subject].nil? ? "Untitled" : params[:subject];
review.body = params[:body]
respond_to do |format|
if review.save
format.html { redirect_to @service, notice: "added review" }
else
format.html { redirect_to @service, error: "Unable to rate service, errors #{review.errors.full_messages }" }
end
end
end
end
# routes.rb
MyApp::Application.routes.draw do
resources :products do
member do
post :review, to: :create_review # POST /products/:id/review
end
end
resources :services do
member do
post :review, to: :create_review # POST /serices/:id/review
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment