here’s what I want to do:
class Foo < ActiveRecord::Base
has_many :bars
end
class Bar < ActiveRecord::Base
belongs_to :foo
acts_as_hash :scope => :foo_id, :key => :keycolumn
end
foo = Foo.find(…)
bar = foo.bars[‘my_key’]
Is there an existing acts_as_hash plugin, or any other good way to do
this?
Brian,
hello first,
foo = Foo.find(…)
bar = foo.bars[‘my_key’]
Is there an existing acts_as_hash plugin, or any other good way to do
this?
I’m not sure to understand well what you want to do, but if you
want given a foo record, from the collection of bars associated with,
to retrieve one with a given condition, you can do sth like that
(using association extensions) :
class Foo < AR::B
has_many :bars do
def
find(:first, :conditions => [‘my_column = ?’, key.to_s])
end
end
end
then bar = foo.bars[‘hello’] will be the record with
foo_id = foo.id and my_column = ‘hello’.
hope it helps,
– Jean-François.
–
Ã? la renverse.
On Oct 2, 2006, at 7:07 AM, Jean-François wrote:
belongs_to :foo
want given a foo record, from the collection of bars associated with,
then bar = foo.bars[‘hello’] will be the record with
foo_id = foo.id and my_column = ‘hello’.
hope it helps,
– Jean-François.
Here is a little DbHash model I have used in the past. You could add
a foreign key to it so it works with your relationship.
class DbHash < ActiveRecord::Base
class << self
def
pair = find_by_key(key.to_s)
pair.value unless pair.nil?
end
def []=(key, value)
pair = find_by_key(key)
unless pair
pair = new
pair.key, pair.value = key.to_s, value
pair.save
else
pair.value = value
pair.save
end
value
end
def to_hash
Hash[ *find_all.map { |pair| [pair.key, pair.value] }.flatten ]
end
end
end
create_table "db_hashes", :force => true do |t|
t.column "key", :string, :limit => 40, :default => "", :null
=> false
t.column “value”, :string, :default => “”
end
-EZra