Last active
September 9, 2015 01:55
-
-
Save larryisthere/a17366a8be29ec124500 to your computer and use it in GitHub Desktop.
I got a Completed 500 Internal Server Error when I saved a duplicated record to a table which has validate of uniqueness and a composite index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
User can like products, but as one product it should only be liked by one user once. So I add a composite index of product_id and user_id on table like and add a validate on model like. | |
Here is the codes: | |
like.rb | |
class Like < ActiveRecord::Base | |
belongs_to :user | |
belongs_to :product | |
accepts_nested_attributes_for :product | |
validates :user_id, uniqueness: { | |
scope: :product_id | |
} | |
end | |
likes_controller.rb | |
class LikesController < ApplicationController | |
def create | |
@like = Like.new user_id: current_user.id, | |
product_id: like_params[:product_id] | |
@like.product.increment :likenumber | |
respond_to do |format| | |
if @like.save | |
format.json { render json: @like, status: :created } | |
else | |
format.json { render json: @like.errors, status: :nprocessable_entity } | |
end | |
end | |
end | |
def destroy | |
end | |
private | |
def like_params | |
params.permit(:product_id) | |
end | |
end | |
show.html.erb | |
<%= link_to raw("<i class=\"fa fa-heart-o fa-2x\"></i><i class=\"fa fa-heart fa-2x\"></i><br><span class=\"label\">#{@product.likenumber}</span>"), [@product, @like], remote: true, method: :post, :class => "slidebutton like" %> | |
Here is the server log: | |
Started POST "/products/4/likes" for 10.0.1.14 at 2015-09-09 09:53:09 +0800 | |
Processing by LikesController#create as JS | |
Parameters: {"product_id"=>"4"} | |
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1 | |
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = $1 LIMIT 1 [["id", 4]] | |
(0.1ms) BEGIN | |
Like Exists (0.2ms) SELECT 1 AS one FROM "likes" WHERE ("likes"."user_id" = 1 AND "likes"."product_id" = 4) LIMIT 1 | |
(0.1ms) ROLLBACK | |
Completed 500 Internal Server Error in 9ms (Views: 0.3ms | ActiveRecord: 0.9ms) | |
And the real response: | |
{"user_id":["Has been taken."]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment