Skip to content

Instantly share code, notes, and snippets.

@mrinterweb
Created July 28, 2009 02:24
Show Gist options
  • Save mrinterweb/156884 to your computer and use it in GitHub Desktop.
Save mrinterweb/156884 to your computer and use it in GitHub Desktop.
class Favorite < ActiveRecord::Base
# Uses composite_primary_keys gem: http://compositekeys.rubyforge.org/
set_primary_keys :user_id, :location_id
belongs_to :user
belongs_to :location
validates_uniqueness_of :user_id, :scope => :location_id
end
class FavoritesController < ApplicationController
# ...
def create
favorite = Location.find(params[:location_id])
@user.favorites << favorite
if @user.save
flash[:notice] = "Successfully created favorite."
respond_to do |format|
#format.html redirect_to @favorite
format.xml { render :xml => favorite }
format.js { render :json => favorite }
end
else
respond_to do |format|
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
format.js { render :json => @user.errors, :status => :unprocessable_entity }
end
end
end
# ...
end
require File.dirname(__FILE__) + '/../spec_helper'
describe FavoritesController do
integrate_views
before(:each) do
@user = Factory.create(:user)
@location = Factory.create(:location_1)
@user.favorites << @location
@user.save!
controller.stub!(:fetch_user).and_return(@user)
end
it "create action should fail when duplicate entries are submitted with JSON request" do
post :create, :location_id => @location.id, :format => 'js'
puts ">>> THE FOLLOWING SHOULD FAIL >>>\n"
puts response.body
json = ActiveSupport::JSON.decode(response.body)
json.count.should == 1
json["location"]["id"].should == location_2.id
puts "CREATE JSON: \n#{response.body}\n"
end
end
Notes:
I have a unique composite primary key/index set in MySQL for the fields: user_id and location_id.
I expect an error to be thrown, but I am unable to recover from the following error.
For some reason it is not validating_uniqueness_of [:user_id, :location_id] before it tries to insert a record.
Error:
ActiveRecord::StatementInvalid (Mysql::Error: Duplicate entry '7-2' for key 'index_favorites_on_user_id_and_location_id':
INSERT INTO `favorites` (`created_at`, `updated_at`, `user_id`, `location_id`) VALUES ('2009-04-25 01:50:47', '2009-07-24 06:34:59', 7, 2)):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment