Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using has_many belongs_to #7

Open
dja opened this issue Aug 13, 2014 · 3 comments
Open

Using has_many belongs_to #7

dja opened this issue Aug 13, 2014 · 3 comments

Comments

@dja
Copy link

dja commented Aug 13, 2014

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?

@hzamani
Copy link
Owner

hzamani commented Aug 14, 2014

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

@dja
Copy link
Author

dja commented Aug 15, 2014

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

@filipegiusti
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants