Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a gem with associated Rails models
    text
    copied!<p>I would like to package a gem that includes ActiveRecord models that can be associated with models in the existing Rails application. I've been trying to follow the code for acts_as_taggable_on, but I'm running into some problems getting the associations to work.</p> <p>My gem is called Kitchen. My model defined in the gem is Dish, and I want to add a polymorphic association (as Cook) to a model in the main application such as User.</p> <p>In <code>lib/kitchen.rb</code></p> <pre><code>require "active_record" require "kitchen/dish.rb" require "kitchen/cook.rb" </code></pre> <p>In <code>lib/kitchen/dish.rb</code></p> <pre><code>module Kitchen class Dish &lt; ::ActiveRecord::Base belongs_to :cook, :polymorphic =&gt; true end end </code></pre> <p>In <code>lib/kitchen/cook.rb</code> (lifting code from <a href="http://guides.rubyonrails.org/plugins.html#add-an-acts_as-method-to-active-record" rel="nofollow">http://guides.rubyonrails.org/plugins.html#add-an-acts_as-method-to-active-record</a> without much understanding)</p> <pre><code>module Kitchen module Cook extend ActiveSupport::Concern included do end module ClassMethods def acts_as_cook class_eval do has_many :dishes, :as =&gt; :cook end end end end end ActiveRecord::Base.send :include, Kitchen::Cook </code></pre> <p>Finally, I've migrated everything in my dummy app, and include the association in <code>spec/dummy/app/models/user.rb</code></p> <pre><code>class User &lt; ActiveRecord::Base acts_as_cook end </code></pre> <p>I'm getting an error any time I try to access <code>user.dishes</code> for a User instance:</p> <pre><code> NameError: uninitialized constant User::Dish </code></pre> <p>Any idea what's missing? </p>
 

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