【问题标题】:What is <ActiveRecord::Associations::CollectionProxy []>?<ActiveRecord::Associations::CollectionProxy []> 是什么?
【发布时间】:2013-12-11 17:16:27
【问题描述】:

我有这些模型:

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。

谢谢大家。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

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

    has_many :categories, through: :item_categoryships
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 2014-04-26
      • 1970-01-01
      相关资源
      最近更新 更多