Forum: Ruby on Rails Including join model data

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6fd237f6f40f5afca32aca6ea633f58a?d=identicon&s=25 Tom Lobato (Guest)
on 2009-01-04 22:50
(Received via mailing list)
I`m using the joing model Part to access Treinando from Evento.
This code works well:

   @treinandos = Evento.find(params[:evento_id]).treinandos

But the parts table has some more columns I need to retrieve
addtionally.
Even after some docs/googling and tests I was not able to append this
information to the resulting object @treinandos.

Can you give some hints about how to do it?

Models:

class Treinando < ActiveRecord::Base
  has_many :parts
  has_many :eventos, :through => :parts
end
class Part < ActiveRecord::Base
  belongs_to :treinando
  belongs_to :evento
end
class Evento < ActiveRecord::Base
  has_many :parts
  has_many :treinandos, :through => :parts
end
6fd237f6f40f5afca32aca6ea633f58a?d=identicon&s=25 Tom Lobato (Guest)
on 2009-01-05 00:59
(Received via mailing list)
Well, I found a way, but it is not a optimized (rails way) one, since
it executes a find for each "part" record, more some selects.

    parts = Evento.find(params[:evento_id]).parts
    @treinandos = []
    parts.each do |part|
      obj = Treinando.find(part.treinando_id)
      obj[:padrinho] = part.padrinho.nome if part.padrinho_id
      obj[:presenca] = part.presenca
      @treinandos << obj
    end

If you have any idea about the rails way to do it, please tell me.
This topic is locked and can not be replied to.