什么是<activerecord :: associations :: collectionproxy [] =“”>?</activerecord :: associations :: collectionproxy>

时间:2013-12-11 09:10:48

标签: ruby-on-rails activerecord

我有这些模特:

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。

谢谢大家。

1 个答案:

答案 0 :(得分:0)

ActiveRecord::Associations::CollectionProxy是集合关联的ActiveRecord类。现在,如果您将描述Item关联的categories类中的行更改为:

,那么您的代码应该可以正常工作
has_many :categories, through: :item_categoryships