Creating has_many :through records 2x times
Posted
by antiarchitect
on Stack Overflow
See other posts from Stack Overflow
or by antiarchitect
Published on 2010-05-18T01:32:56Z
Indexed on
2010/05/18
1:40 UTC
Read the original article
Hit count: 299
ruby-on-rails
|has-many-through
I have models
class Question < ActiveRecord::Base
WEIGHTS = %w(medium hard easy)
belongs_to :test
has_many :answers, :dependent => :destroy
has_many :testing_questions
end
class Testing < ActiveRecord::Base
belongs_to :student, :foreign_key => 'user_id'
belongs_to :subtest
has_many :testing_questions, :dependent => :destroy
has_many :questions, :through => :testing_questions
end
So when I try to bind questions to testing on it's creation:
>> questions = Question.all
...
>> questions.count
=> 3
>> testing = Testing.create(:user_id => 3, :subtest_id => 1, :questions => questions)
Testing Columns (0.9ms) SHOW FIELDS FROM `testings`
SQL (0.1ms) BEGIN
SQL (0.1ms) COMMIT
SQL (0.1ms) BEGIN
Testing Create (0.3ms) INSERT INTO `testings` (`created_at`, `updated_at`, `user_id`, `subtest_id`) VALUES('2010-05-18 00:53:05', '2010-05-18 00:53:05', 3, 1)
TestingQuestion Columns (0.9ms) SHOW FIELDS FROM `testing_questions`
TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(1, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31)
TestingQuestion Create (0.4ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(2, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31)
TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(3, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31)
TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(1, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31)
TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(2, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31)
TestingQuestion Create (0.3ms) INSERT INTO `testing_questions` (`question_id`, `created_at`, `updated_at`, `testing_id`) VALUES(3, '2010-05-18 00:53:05', '2010-05-18 00:53:05', 31)
SQL (90.2ms) COMMIT
=> #<Testing id: 31, subtest_id: 1, user_id: 3, created_at: "2010-05-18 00:53:05", updated_at: "2010-05-18 00:53:05">
There is 6 SQL queries and 6 records in testing_questions are created. Why?
© Stack Overflow or respective owner