Gm11
(Gm)
March 24, 2015, 6:50pm
1
Hi,
I’m using habtm to create a relationship between two models:
class Question < ActiveRecord::Base
has_and_belongs_to_many :exams
end
class Exam < ActiveRecord::Base
has_and_belongs_to_many :questions
end
At some point I’m doing this:
class Exam < ActiveRecord::Base
has_and_belongs_to_many :questions
def generate
(1…5).each do
questions.create(Question::SKELETON)
end
end
end
When I do that, a sql inserts a record inside questions_exams table.
But this table has another column called: ‘order’ where I need to put some data inside
How can I populate the ‘order’ column inside join table ?
questions_exams
- order
Thanks.
Colin_Law
(Colin Law)
March 24, 2015, 9:11pm
2
Don't use habtm, use has many through
Exam has_many questions_exams
has_many questions through questions_exams
But probably don't call it questions_exams, think of a better name
In fact even when I could use habtm I usually use has many through, I
find it easier to understand. Also it is surprising how often the
requirement for a little something extra in the join table pops up out
of the requirements when least expected.
Colin
Gm11
(Gm)
March 26, 2015, 8:38pm
3
Hi Colin,
Thanks for the reply.
Even if I use has many through, how can I populate the order field dinamically ?
When I do this:
def generate
(1…5).each do
questions.create(Question::SKELETON)
end
end
Thank you.
Colin_Law
(Colin Law)
March 26, 2015, 9:07pm
4
Hi Colin,
Thanks for the reply.
Even if I use has many through, how can I populate the order field
dinamically ?
When I do this:
def generate
(1..5).each do
questions.create(Question::SKELETON)
end
end
Possibly something like
exam.questions_exams.create(order: something).create_question(...)
You can find detailed definitions of the methods that the associations
provide in section 4 of
Colin