我有这些模特:
class Item < ActiveRecord::Base
has_many :item_categoryships
has_many :categories, class_name: 'ItemCategoryship', foreign_key: 'category_id', :through => :item_categoryships
belongs_to :user
validates :title, presence: true
端
class Category < ActiveRecord::Base
has_many :item_categoryships
has_many :items, :through => :item_categoryships
belongs_to :user
validates :name, presence: true
end
class ItemCategoryship < ActiveRecord::Base
belongs_to :item
belongs_to :category
validates :item_id, presence: true
validates :category_id, presence: true
end
class User < ActiveRecord::Base
has_many :items
has_many :categories, class_name: 'Category'
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :async
end
但我发现当我调用item.categories时会得到一个空数组!!!我检查了数据库,这里有一条记录。
当我在rails控制台中测试时,我没有收到任何记录,只看到'ActiveRecord :: Associations :: CollectionProxy []'。
这是什么?我正在使用Rails 4.0.2。谢谢大家。
答案 0 :(得分:0)
ActiveRecord::Associations::CollectionProxy
是集合关联的ActiveRecord
类。现在,如果您将描述Item
关联的categories
类中的行更改为:
has_many :categories, through: :item_categoryships