Using has_many belongs_to
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

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?
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
Thanks @hzamani. That works for retrieving photos, but doesn't work when creating them..
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