active_record-acts_as icon indicating copy to clipboard operation
active_record-acts_as copied to clipboard

Using has_many belongs_to

Open dja opened this issue 11 years ago • 3 comments

I'm trying to setup a relation between a Company, and the Media that is associated with the Company, and I'm having trouble finding how to store the parent id on the join table (and not each individual child class in the join table)

Right now, I have

class Company < ActiveRecord::Base
   has_many :company_media
   has_many :media, through: :company_media
end
class Media < ActiveRecord::Base
   actable
   has_many :company_media
   has_many :companies, through: :company_media
end
class CompanyMedia < ActiveRecord::Base
   belongs_to :company
   belongs_to :media
end
class Photo < ActiveRecord::Base
   acts_as :media
end
class Video < ActiveRecord::Base
   acts_as :media
end

screenshot 2014-08-13 14 45 30

What I really want:

class Photo < ActiveRecord::Base
   acts_as :media
   has_many :company_media
   has_many :companies, through: :company_media
end
class Company < ActiveRecord::Base
   has_many :company_media
   has_many :photos, through: :company_media
   has_many :videos, through: :company_media
end

Essentially, I need the ability to say, company.photos.create and have it create a new Photo (with info in the Media and Photo tables), but store the Photo's media.id in the CompanyMedia table.

Has anyone made this happen successfully yet?

dja avatar Aug 13 '14 21:08 dja

What about this:

class Company < ActiveRecord::Base
  has_many :company_media

  def photos
    CompanyMedia.joins(:media).where(company_id: id, media: {actable_type: 'Photo'})
  end
end

hzamani avatar Aug 14 '14 13:08 hzamani

Thanks @hzamani. That works for retrieving photos, but doesn't work when creating them..

dja avatar Aug 15 '14 19:08 dja

I haven't tested but I would expect the below to work.

class Company < ActiveRecord::Base
   has_many :company_media
   has_many :photos, -> { where(actable_type: 'Photo') }, through: :company_media
   has_many :videos, -> { where(actable_type: 'Video') }, through: :company_media
end

filipegiusti avatar Sep 26 '14 02:09 filipegiusti