【问题标题】:How to override activerecord's default attribute column associations?如何覆盖activerecord的默认属性列关联?
【发布时间】:2009-07-21 22:27:05
【问题描述】:

我正在开发一个完全没有意义的遗留数据库。我有一个名为movie 的表,其中包含名称为c00、c01、c02 等的列。该表还使用非标准的primary_keys。所以我创建了一个像这样的电影类:

class Movie < ActiveRecord::Base
  set_table_name "movie"
  set_primary_key "idMovie"

  belongs_to :media_file, :foreign_key => "idFile" 

  def title
    self.c00
  end

  def plot
    self.c01
  end
end

我希望能够执行类似 Movie.find_by_title("Die Hard") 的操作并让它返回正确的结果。我也想说 Movie.create(:title => "Die Hard")。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby database activerecord legacy


    【解决方案1】:

    我想你想要alias_attribute。查看今年 RailsConf 的Brian Hogan's excellent presentation。

    【讨论】:

    • 太棒了!这消除了对定义访问器和修改器的方法的需求,但它不允许我通过别名进行搜索。所以 Movie.find_by_title("Die Hard") 还是不行。
    【解决方案2】:

    你真的只需要 Sarah's answer 和 Ben's answer 的组合:

    class Movie < ActiveRecord::Base
    
      # gives you Movie.find_by_title
      # and lets you chain with other named scopes
      named_scope :find_by_title, lambda { |title| { :conditions => { :c00 => title } } }
    
      # gives you
      #   movie.title
      #   movie.title=(title)
      # and
      #   Movie.new(:title => title)
      alias_attribute :title, :c00
    
    end
    

    【讨论】:

      【解决方案3】:

      find_by_* 方法使用反射,因此在开箱即用的 Rails 中不会发生这种情况。当然,您可以定义自己的方法:

      def self.find_by_title(title)
          first(:conditions => { :c00 => title })
      end
      

      下一步将遍历 column_aliases => real_columns 的哈希值,以用作调用 alias_attribute 和 define_method 的素材。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多