I have something like this:
class Person < ActiveRecord::Base
has_many :things do
def [](kind)
find(:first, :conditions => ["kind = ?", kind.to_s])
end
def []=(kind, config)
thing = self[kind]
if thing.nil?
#create new thing
ap self # prints all things that person has
else
# update
end
end
end
With the above code, I can do something like person.things[:table] and it will find a thing with person_id of whatever person’s id is, and kind of table. The first method is fine.
It’s the second method that I don’t know how to implement.
If I want to set the configuration of a table, I want to do it like this person.things[:table] = {:my => "config"}
That will be fine if the table already exists.
But what if I want to create a new thing?
Normally, creating a Thing would look like this:
thing = Thing.new({
person_id => person[:id],
kind => "table"
config => {}
})
but, since I’m doing an association extension, and want to create a new object, how do I get the person id?
using
ruby 1.8.7
rails 2.3.14
I haven’t used this recently, but have you tried
inside the extension? This should return the
Person, I believe.Documentation: RoR Guides.
Edit: I just noticed that in your example, a
Personis not an ActiveRecord model? Was that an omission?For Rails 2.3.14, you want to use AssociationProxy’s
proxy_ownermethod.then just do
things.proxy_owner[:id]