When I create a new pet, the pet is associated with a User through
habtm. These are the classes:
class Pet < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :pets
validates_uniqueness_of :screen_name, :email
end
This is the code in the controller for adding the new pet, which updates
the join table:
@pet = Pet.new(params[:pet])
@user = User.find_by_id(user_id)
@pet.users << @user
@pet.save
This makes a lot of calls to the database:
SHOW FIELDS FROM users
SELECT * FROM users
WHERE (users
.id
= ‘11’) LIMIT 1
BEGIN
COMMIT
BEGIN
(these next two lines are validations)
SELECT * FROM users
WHERE (users.screen_name = ‘chairs’ AND users.id
<> 11) LIMIT 1
SELECT * FROM users
WHERE (users.email = ‘[email protected]’ AND users.id
<> 11) LIMIT 1
INSERT INTO pets
(name
, updated_at
, description
, created_at
)
VALUES(‘Kitty Kitty’, ‘2008-02-28 18:08:36’, ‘Lost cat in Washington.’,
‘2008-02-28 18:08:36’)e
INSERT INTO users_pets (user_id
, pet_id
) VALUES (11, 2)e
COMMIT
Is there any way of reducing the number of calls to the database? Is
there a way to suppress the validation calls? I also don’t understand
why it makes the first BEGIN/COMMIT calls. Or is there a better way to
do this that is more efficient? I could do custom SQL commands, but I
was hoping to do it the rails way.