Query thru association

25 views
Skip to first unread message

Dave Castellano

unread,
Nov 6, 2014, 10:07:14 PM11/6/14
to rubyonra...@googlegroups.com
Hi,

I'm stuck trying to figure out how to do a query to find all the
questions in a selected subject only.

My associations:

class Subject < ActiveRecord::Base
has_many :books
has_many :questions
has_many :chapters, :through => :books
has_many :sections, :through => :chapters
has_many :subsections, :through => :sections
has_many :minisections, :through => :subsections

class Question < ActiveRecord::Base
has_and_belongs_to_many :minisections

The query:
@question_list = Question.where(all the questions associated with the
subject through the above associations???)

Any suggestions where to start would be appreciated.

Thanks,
Dave

--
Posted via http://www.ruby-forum.com/.

Colin Law

unread,
Nov 7, 2014, 3:51:57 AM11/7/14
to rubyonra...@googlegroups.com
On 7 November 2014 03:05, Dave Castellano <li...@ruby-forum.com> wrote:
> Hi,
>
> I'm stuck trying to figure out how to do a query to find all the
> questions in a selected subject only.
>
> My associations:
>
> class Subject < ActiveRecord::Base
> has_many :books
> has_many :questions
> has_many :chapters, :through => :books
> has_many :sections, :through => :chapters
> has_many :subsections, :through => :sections
> has_many :minisections, :through => :subsections
>
> class Question < ActiveRecord::Base
> has_and_belongs_to_many :minisections
>
> The query:
> @question_list = Question.where(all the questions associated with the
> subject through the above associations???)

@question_list = @subject.questions

Note, though, that since you have subject has_many questions you also
need question belongs_to subject. Also you need to re-think your
associations as you have two routes to question from subject -
directly through the has_many but also right through the chain of
chapters, etc.

Colin

Dave Castellano

unread,
Nov 10, 2014, 3:03:04 PM11/10/14
to rubyonra...@googlegroups.com
Colin Law wrote in post #1161913:
Thank you!
Reply all
Reply to author
Forward
0 new messages