Search code examples
ruby-on-railsactiverecordhas-manyhas-one

Rails: building object from has_many associated object


I think it might be a syntax problem.

  1. I have a Event.rb model:

    class Event < ActiveRecord::Base
     belongs_to :members
     has_one :brazusc
    end
    

    A Member.rb:

    class Member < ActiveRecord::Base
     has_many :events
    end
    

    And a Brazusc.rb model:

    class Brazusc < ActiveRecord::Base
     belongs_to :event
    end
    

What I am trying to do: member.events.build_brazusc, but I get:

NoMethodError: undefined method `build_brazusc' for #<Event::ActiveRecord_Associations_CollectionProxy:0x007f99517d4a78>

How would I build an object from the has_many association?

  1. I am also trying to retrieve the associated model from a has_many/has_one association, like this: member.events.brazusc, since brazusc has an event_id, but I get:

    NoMethodError: undefined method `leads' for #<Event::ActiveRecord_Associations_CollectionProxy:0x007f99517d4a78>
    

How can I retrieve the object (brazusc) that is associated with event?

Any help will be much appreciated.


Solution

  • This would do the trick:

    new_brazusc = member.events.find_by(name: "Brazusc")
    new_brazusc.build_brazusc.save