Kevin Alons wrote the following on 18.07.2007 05:58 :
I am new to Rails development, having done c++ and other database driven
app development in the past. Often I would create a database view that
would combine, for example, first and last name values into a "virtual"
field called FullName.
I don't see how to use database views with Rails, so I am thinking that
another way to this would be to define a virtual attribute on the
appropriate class to do the same thing (the derived ActiveRecord or
ApplicationController classes?), but I am unclear where and how this
should be declared.
Can anyone point me in the right direction?
For this particular need, a simple 'full_name' method in your model is probably simpler.
If you need to affect names by full name, you can code a full_name= method too.
It's probably better because:
- much simpler to handle, all your logic is in one place: the model,
- Ruby is more powerful than pure SQL (ie: your full_name will be easier to code and extend),
- doing it in the model instead of the DB is more flexible, a model has access to code (libraries) you can share easily with other parts of your application (most likely other models),
- you don't have to aggregate data accross rows or join tables to get at this data, so doing it in the model can't be a problem for performance (which is not to say that you'll get better perf using views when joins are implicated), in fact accessing the DB only once to instanciate the model will yield better performance in your case.