Search code examples
ruby-on-railsmongoidnested-attributes

Mongoid and Rails: Nested Fields


I'm using Mongoid and for my app, I have a Course, Section, and Lesson model. A course has_many sections, a section belongs_to a course and has_many lessons, and a lesson belongs_to a section. When I try

some_course.some_section.lessons.create()

I get this error: NoMethodError: undefined method `lessons' for Mongoid::Criteria

I tried doing something like this:

#Course.rb 
has_many :sections, -> { includes :lessons }

And I get an error: No implicit conversion of Proc into Hash

How might I be able to create a lesson into a section, which is in a course like this:

some_course.some_section.lessons.create()

?


Solution

  • As you have mentioned, a Course has_many sections. So when you do some_course.sections you get a Criteria (a.k.a a database iterator) to iterate over all the sections that belong to some_course. Even when you apply a condition on the sections so that it matches only one section, you still get back a Criteria.

    i.e some_course.sections.where(id: 'unique_section_id') returns a criteria. If you want the actual Section object use the first method on the criteria.

    i.e some_course.sections.where(id: 'unique_section_id').first

    Note that some_course.sections.first also works, but you are not always sure which section you will get back.