In my models I represent some relations (views/tables) with attributes that you are not allowed to insert or update. These constraints are enforced through some triggers that set them to an automatically generated value that is not to be tampered with. To make this more clear to the users, these triggers throw an exception when the user _does_ try to manually set such an attribute. Active Record, however, doesn''t know about this and, on updates, tries to simply (re)set all fields. Is there some way to make AR treat some given attributes as read-only? - Rowan -- Morality is usually taught by the immoral.
Julian ''Julik'' Tarkhanov
2005-Jul-06 16:19 UTC
Re: Marking attributes as read-only in Active Record
On 5-jul-2005, at 20:59, BigSmoke wrote:> In my models I represent some relations (views/tables) with > attributes that > you are not allowed to insert or update. These constraints are > enforced through > some triggers that set them to an automatically generated value that > is not to be > tampered with. To make this more clear to the users, these triggers > throw > an exception when the user _does_ try to manually set such an > attribute. > > Active Record, however, doesn''t know about this and, on updates, > tries to > simply (re)set all fields. > > Is there some way to make AR treat some given attributes as read-only?I don''t think so, but you can stub them with accessors that throw class Entity < ActiveRecord::base def temperature=(nt) raise "This attribute cannot be modified" end end AR will then try to use this accessor everytime the user tries to do an assignment (also when you do @entity[:temperature] = ''bla'' or @entity.update_attributes(@params). I am sure you can come up with some class method that will generate these pseude setters for you using class_eval. -- Julian "Julik" Tarkhanov