Monday, November 11, 2013

[Rails] Re: has_many question

Dave Castellano wrote in post #1126985:
> Hi all,
>
> I need some guidance please.
>
> I have several tables related by "has_many" and I would like to find the
> "distant children".
>
> Tables:
> Subjects
> Books
> Chapters
> Sections
> Subsections
> Minisections
>
> They are all related heirarchichally, so book for example is related to
> subjects and chapters the following way. All are related the same way.
> Book
> belongs_to :subject
> has_many :chapters
>
> So if I have the subject id, how can I find all the Minisections
> belonging to that subject?

Database normalization is a good thing... until it isn't. I fear you've
run into one of those situations where de-normalization might be very
useful for the sake of efficiency.

Instead of doing a fully hierarchical structure you could flatten parts
of it. For example your Minisection could have id, subject_id, book_id,
chapter_id, section_id, subsection_id and then:

Minisection
belongs_to :subject
belongs_to :book
belongs_to :chapter
belongs_to :section
belongs_to :subsection

Now you can find any list mini-section without using any joins in any
way you see fit.

minisections = Minisection.where({ subject: my_subject, book: my_book,
chapter: my_chapter, section: my_section, subsection: my_subsection }

--
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 unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/c4bf1a0cb88cd96d391cfca4ec5c21a2%40ruby-forum.com.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate