Override ActiveRecord attribute methods

前端 未结 4 1864
臣服心动
臣服心动 2020-12-07 07:39

An example of what I\'m talking about:

class Person < ActiveRecord::Base
  def name=(name)
    super(name.capitalize)
  end
  def name
    super().downcas         


        
4条回答
  •  [愿得一人]
    2020-12-07 08:26

    I have a rails plugin that makes attribute overriding work with super as you would expect. You can find it on github.

    To install:

    ./script/plugin install git://github.com/chriseppstein/has_overrides.git
    

    To use:

    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
    

    Once you've done that things just work:

    $ ./script/console 
    Loading development environment (Rails 2.3.2)
    >> post = Post.new(:title => "a simple title")
    => #
    >> 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"
    

提交回复
热议问题