Can I initialize model attributes from SQL?

Hello,

Is it possible to initialize model attributes from a SQL select
element that's not backed by a real database column?

For example:

class A << ActiveRecord::Base
     attr_accessor :state_info #Not a db column
     has_many :b, :finder_sql='SELECT b.*, \'#{state_info}\' as
state_info FROM b WHERE b.a_id = #{id}'
end

class B << ActiveRecord::Base
    attr_accessor :state_info #Not a db column
    belongs_to :a
end

a.state_info = "test"
b = a.b.first
#b.state_info is nil, but I want it to be initialized to "test" when
it's returned from the :finder_sql.

I don't think I can accomplish this with an after_find/
after_initialize callback either, since I need to have access to the
value of a.state_info in order to set b.state_info.

Thanks,
Tom

Hello,

Is it possible to initialize model attributes from a SQL select
element that's not backed by a real database column?

For example:

class A << ActiveRecord::Base
    attr_accessor :state_info #Not a db column
    has_many :b, :finder_sql='SELECT b.*, \'#{state_info}\' as
state_info FROM b WHERE b.a_id = #{id}'
end

class B << ActiveRecord::Base
   attr_accessor :state_info #Not a db column
   belongs_to :a
end

a.state_info = "test"
b = a.b.first
#b.state_info is nil, but I want it to be initialized to "test" when
it's returned from the :finder_sql.

I'm assuming that :finder_sql=' is a typo for :finder_sql=>'
In activerecord any column in the sql result ends up being accessible.
In this case the attr_accessor you've got on B is actually clobbering
the state_info column.

Fred

Thanks Fred,

The problem is that I need a transient variable on the models (e.g.
attr_accessor :state_info). There are other models, A, B, C, D,...
chained together by foreign key, and transient :state_info. I need to
use the value of :state_info as criteria in the finder_sql in each
link of the chain. So, the chain is traversed differently depending
on how the root object's state_info is initialized.

Is there any way to keep the attr_accessor on the models and also load
the select-element into it with finder_sql?