Note that there are some explanatory texts on larger screens.

plurals
  1. POConflicting associations in has_many_polymorphs
    primarykey
    data
    text
    <p>I'm using has_many_polymorphs to create a "Favorites" feature on a site where multiple users can post stories and make comments. I want users to be able to "favorite" stories and comments.</p> <pre><code>class User &lt; ActiveRecord::Base has_many :stories has_many :comments has_many_polymorphs :favorites, :from =&gt; [:stories, :comments] end class Story &lt; ActiveRecord::Base belongs_to :user, :counter_cache =&gt; true has_many :comments end class Comment &lt; ActiveRecord::Base belongs_to :user, :counter_cache =&gt; true belongs_to :story, :counter_cache =&gt; true end class FavoritesUser &lt; ActiveRecord::Base belongs_to :user belongs_to :favorite, :polymorphic =&gt; true end </code></pre> <p>Now say @user writes a story. Now @user.stories.size = 1. Then @user favorites a different story. Now @user.stories... wait a minute. @user has_many :stories and :has_many :stories through :favorites.</p> <p>The issue arises when I attempt to call @user.stories or @user.comments. I want to call @user.stories for stories they own and @user.favorites.stories for stories they favorite.</p> <p>So I tried this:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :stories has_many :comments has_many_polymorphs :favorites, :from =&gt; [:favorite_stories, :favorite_comments] end </code></pre> <p>and then subclassed Story and Comment like so:</p> <pre><code>class FavoriteStory &lt; Story end class FavoriteComment &lt; Comment end </code></pre> <p>That fixed the problem because now I can call @user.stories and @user.favorite_stories.</p> <p><strong>BUT</strong> when I get this error in reference to comments: </p> <p><strong>ActiveRecord::Associations::PolymorphicError in UsersController#show</strong> </p> <pre><code>Could not find a valid class for :favorite_comments (tried FavoriteComment). If it's namespaced, be sure to specify it as :"module/favorite_comments" instead. </code></pre> <p>I found discussion of this error in a <a href="https://github.com/fauna/has_many_polymorphs/issuesearch?state=open&amp;q=PolymorphicError#issue/2" rel="nofollow">similar context</a>, but it doesn't answer my question.</p> <p>What's going on here? How can I do this better?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload