使用时如何使用内存中对象:has_many和:belongs_to

时间:2011-01-09 23:09:34

标签: ruby-on-rails activerecord

我正在使用Rails 3的Active Record。我有一个类has_many类的用户。我想从共享相同的内存中用户实例的用户实例化类别。

默认的Active记录行为为每个类别创建一个新的用户实例。有什么方法可以改变这种行为吗?

以下是我的代码的一些片段。您可以注意到我尝试使用:inverse_of,但没有成功......

class Category < ActiveRecord::Base
  attr_accessor :name
  attr_accessible :name, :user

  belongs_to  :user, :inverse_of => :categories
end

class User < ActiveRecord::Base
  attr_accessor :key
  attr_accessible :categories, :key

  has_many :categories, :inverse_of => :user
end

我有以下规范来测试所需的行为:

user = User.first
user.key = @key  # key is an :attr_accessor, not mapped to db

category = user.categories.first
category.user.key.should == user.key  # saddly, it fails.. :(

有什么建议吗?

感谢您阅读我的问题!

0 个答案:

没有答案
相关问题