SRack
SRack

Reputation: 12213

Rails polymorphic associations and database queries

I've a problem with a couple of polymorphic associations. I'm trying to connect both Users and Recipes to shared Dietary Requirements (DRs) through polymorphic associations, with the dietary requirements available to many-to-many of each.

I've created a Dietary Requirement to test this (Vegetarian), though am having trouble accessing this in the page view. I think the reason for this is that the DR created has the classifiable_type Recipe, meaning when the database query runs, I can't access this particular instance for my Users as SQLite automatically looks for a classifiable_type of User. Also, as it stands, each DR appears to have to belong to a specific User or Recipe, while I'd like them all available to many (or am I wrong here?)

In the console, I can see both User.first.dietary_requirements and Recipe.first.dietary_requirements, though in the view I can't access these, because of the reasons above.

Is there a way to circumvent this problem and get my view showing a list of User DRs and Recipe DRs, or will I have to adjust my models to achieve this? Right now I'm planning to switch to more verbose has-many-through relationships, with separate join tables between User - DRs and Recipe - DRs. If there's an alternative, Rails-way to achieve this, it'd be great to hear.

Model code below:

Recipe

has_many :dietary_requirements, as: :classifiable

User

has_many :dietary_requirements, as: :classifiable

Dietary Requirement

belongs_to :classifiable, polymorphic: true

Upvotes: 1

Views: 140

Answers (1)

dostu
dostu

Reputation: 1518

You would need Dietary Requirement to have has_and_belongs_to_many relationship with Users and Recipes, however you cannot have polymorphic HABTM associations. You will need to create a join model for it to work.

More: HABTM Polymorphic Relationship

Upvotes: 1

Related Questions