how to ad a "virtual column" to a model

is it possible to define a column in a model, which is not present in
the table? this column should return a combination of two other columns.

Model.columnC=Model.columnA+"-"+Model.columnB

A and B are in the table, C isn't

I was thinking of attr_accessor, but i cant get it to work

any pointers?

You only need to use attr_accessor if you're looking to set the value as well as get it. You should just be able to create a method to do this:

class Cheese < ActiveRecord::Base
   def name
      origin+" "+type
   end
end

my_cheese = Cheese.new
my_cheese.origin = "Kent"
my_cheese.type = "Stilton"
puts my_cheese.name -> "Kent Stilton"

Hope that helps,

Steve

There might be some misunderstaning here, at lest on my part -

The dataset is a group of objects. When you do: model_instance.name --
you're not really accessing any data, you're calling a method inside
ActiveRecord, (method_missing, actually)

If you had manually defined a method called 'name', there would be no
difference to the code using the model. It just sees a method.

Unless by saying 'the dataset', you mean the model's @attributes
variable?

Cheers
Starr

If performing a find all is your goal with the results being the join of two tables fields why not just find all for each field and use .join to combine their results in a new array. Then just use .each to iterate through that array and/ar access it by its indexes? Perhaps a little bit exhaustive for your goal but it is an option. Im sure there is something more DRY though.

If performing a find all is your goal with the results being the join of two tables fields why not just find all for each field and use .join to combine their results in a new array. Then just use .each to iterate through that array and/ar access it by its indexes? Perhaps a little bit exhaustive for your goal but it is an option. Im sure there is something more DRY though.

Or write a new find method named FindWithVirtualColumn or some such, that writes the actual SQL query you’re trying to emulate. ActiveRecord is great, but don’t be afraid of SQL when neccessary.