Can I somehow setup a Model so that I can prevent a column from being updated aka a read only attribute? I''m thinking that I need to override the "=" operator in my Model class. Am I on the right track? scott. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Scott F. Walterscottwalter.com --explorer what''s new
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Oct 27, 2005, at 2:14 PM, Scott Walter wrote:> Can I somehow setup a Model so that I can prevent a > column from being updated aka a read only attribute? > I''m thinking that I need to override the "=" operator > in my Model class. Am I on the right track?Yup! class Foo def bar=(value) raise "I''m read-only dammit!" end end Also see the new :readonly option to find, which makes the entire record read-only. begin f = Foo.find(:first, :readonly => true) f.save rescue ActiveRecord::ReadOnlyRecord puts "Look, but don''t touch! Thx." end Best, jeremy -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (Darwin) iD8DBQFDYUZMAQHALep9HFYRAia1AJoDUXeXa6SgN48GAKyvhCD/+qJqjQCgq+N5 7+RXEPZV3Lr59XcCg61+qOY=GF7X -----END PGP SIGNATURE-----
Jeremy Kemper wrote:> Yup! > > class Foo > def bar=(value) > raise "I''m read-only dammit!" > end > endI''ve got a question about something related. When you override the "=" operator like this, is it still necessary to protect against mass assignments with "attr_protected"? In other words, does assigning like "model.attributes = hash" use the "=" operator, or does it generate SQL itself? I''m pretty sure it is the former, but thought I''d ask, just to be sure.
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Oct 27, 2005, at 3:38 PM, Wiebe Cazemier wrote:> Jeremy Kemper wrote: >> Yup! >> class Foo >> def bar=(value) >> raise "I''m read-only dammit!" >> end >> end >> > > I''ve got a question about something related. When you override the > "=" operator like this, is it still necessary to protect against > mass assignments with "attr_protected"? In other words, does > assigning like "model.attributes = hash" use the "=" operator, or > does it generate SQL itself? > > I''m pretty sure it is the former, but thought I''d ask, just to be > sure.Yes, attributes= calls each attr_name= method rather than setting the hash directly. To match attr_protected behavior, you''d drop the value on the floor instead of raising an exception: class Foo # Ignore attempts to set bar. def bar=(value) end end jeremy -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (Darwin) iD8DBQFDYV41AQHALep9HFYRAg4+AJsECWMdfjoj077mu92duvPWJ8iv0gCfZs73 au7jTkBcbuYyJT7cabS1nWI=/BUu -----END PGP SIGNATURE-----