Help with habtm

37 views
Skip to first unread message

Gm

unread,
Mar 24, 2015, 2:50:37 PM3/24/15
to rubyonra...@googlegroups.com
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
   - question_id
   - exam_id
   - order

Thanks.

Colin Law

unread,
Mar 24, 2015, 5:11:46 PM3/24/15
to rubyonra...@googlegroups.com
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

Gm

unread,
Mar 26, 2015, 4:38:41 PM3/26/15
to rubyonra...@googlegroups.com
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

unread,
Mar 26, 2015, 5:09:13 PM3/26/15
to rubyonra...@googlegroups.com
On 26 March 2015 at 20:38, Gm <javap...@gmail.com> wrote:
> 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
http://guides.rubyonrails.org/association_basics.html

Colin
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to rubyonrails-ta...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/rubyonrails-talk/b52618bd-253d-4f42-8272-7341dd4ceccf%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages