我正在尝试设置一个简单的has_many:through =>协会。
我有3个型号。 user.rb,icon.rb和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
据我所知,我已经完成了所有事情,但是在尝试在rails控制台中运行以下内容时......
User.first.icons
我收到此错误....
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>'
知道我在这里做错了吗?
答案 0 :(得分:4)
您的问题出在UserIcon模型中的关联中。案例在定义关联时很重要。如果将模型更改为小写,则应该可以正常工作。
class UserIcon < ActiveRecord::Base
belongs_to :user
belongs_to :icon