我有一个Rails插件,可以像您期望的那样使用super进行属性覆盖。您可以在github上找到它。
安装:
./script/plugin install git://github.com/chriseppstein/has_overrides.git
使用方法:
class Post < ActiveRecord::Base
has_overrides
module Overrides
# put your getter and setter overrides in this module.
def title=(t)
super(t.titleize)
end
end
end
完成后,事情就可以了:
$ ./script/console
Loading development environment (Rails 2.3.2)
>> post = Post.new(:title => "a simple title")
=> #<Post id: nil, title: "A Simple Title", body: nil, created_at: nil, updated_at: nil>
>> post.title = "another simple title"
=> "another simple title"
>> post.title
=> "Another Simple Title"
>> post.update_attributes(:title => "updated title")
=> true
>> post.title
=> "Updated Title"
>> post.update_attribute(:title, "singly updated title")
=> true
>> post.title
=> "Singly Updated Title"