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 =
''chairs-+LBmYUDmh58@public.gmane.org'' 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'')
INSERT INTO users_pets (`user_id`, `pet_id`) VALUES (11, 2)
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.
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---