How do I use an in-memory object when working with :has_many and :belongs_to
I am using Active Record with Rails 3. I have a class User that has_many Categories. I would like to instantiate categories from user that shares the same in-memory user instance.
The default Active record behavior creates a new instance of user for each category. There is any way to change this behavior?
Here are some snippets of my code. You can notice that I tried to use :inverse_of, without success...
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, 开发者_JAVA技巧:inverse_of => :user
end
I have the following spec to test the desired behavior:
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.. :(
Any suggestions?
Thank you for reading my question!
精彩评论