Jump to content

The ultimate community for Ruby on Rails developers.


Photo

missing method for child of child of parent


  • Please log in to reply
1 reply to this topic

#1 jstrong

jstrong

    Passenger

  • Members
  • 1 posts

Posted 07 October 2013 - 06:37 PM

I have three models: group, event, note.

 

group has_many :events and has_many :notes

 

events belongs_to :group and has_many :events

 

notes belongs_to :group and belongs_to :event

 

in my routes I am nesting them like

  resources :groups do
    resources :events do
      resources :notes
    end
  end

In my NotesController#create method, I can't get it to work in what I believe is the proper way. The commented line does NOT work - says there is no "notes" method in NotesController#create. I have to resort to the workaround below. Is there something I'm doing wrong here? doesn't the has_many: line in my group and events model create the "notes" method for those classes? Should I possibly eliminate the relationship between the groups and notes models and rely on events to bridge those two? 

    @group = Group.find(params[:group_id])
    @event = Event.find(params[:event_id])
    #@note = @group.events.notes.new(params[:note])
    #that doesn't work, but this manual workaround does:
    @note = Note.new(params[:note])
    @note.group_id = @group.id
    @note.event_id = @event.id


#2 stevieing

stevieing

    Dispatcher

  • Members
  • 40 posts

Posted 09 October 2013 - 07:38 AM

The first thing I would say is that the Rails documentation advises never to nest resources more than 1 level deep due to the complexity.

 

I think there may be an issue with your logic.

 

You say that group has many events and notes in which case an event has no notes which means that @group.event.notes will not work.

 

I wonder if it should be that an event has many notes? In which case you need another association. Even if that were true that would still not work as each event would have many notes so you would need to do something like @group.events.find(params[:event_id]).notes.build(params[:note]).

 

If indeed a group does have many notes then you may need an has_many :through association.

 

It is quite difficult to work out from what you posted unless I am missing something!

 

It is always good to test these things out elsewhere before integrating them into your controller so my advice would be to either have a test suite or use the rails console.

 

Hope that helps...

 

Steve.

 

 


  • james likes this




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users