I’m trying to setup a simple has_many :through => association.
I have 3 models. user.rb, icon.rb and user_icon.rb.
user.rb…
class User < ActiveRecord::Base
has_many :user_icons
has_many :icons, :through => :user_icons
end
icon.rb…
class Icon < ActiveRecord::Base
has_many :user_icons
has_many :users, :through => :user_icons
end
user_icon.rb
class UserIcon < ActiveRecord::Base
belongs_to :User
belongs_to :Icon
end
As far as I can tell I’ve done everything correctly but when trying to run the following in the rails console…
User.first.icons
I get this error….
1.9.2-p290 :002 > User.first.icons
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :icon or :icons in model UserIcon. Try 'has_many :icons, :through => :user_icons, :source => <name>'. Is it one of :User or :Icon?
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/reflection.rb:517:in `check_validity!'
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/associations/association.rb:27:in `initialize'
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/associations/collection_association.rb:24:in `initialize'
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/associations.rb:159:in `new'
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/associations.rb:159:in `association'
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.1/lib/active_record/associations/builder/association.rb:41:in `block in define_readers'
from (irb):2
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/commands/console.rb:45:in `start'
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/commands/console.rb:8:in `start'
from /Users/jon/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Any idea what I’m doing wrong here?
Your problem is in your associations in the UserIcon model. Case is important in defining your associations. If you change the models to lower case, it should work.