【发布时间】: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