Rails primary_key没有继承

时间:2016-06-01 06:30:30

标签: ruby-on-rails schema-plus

我使用优秀的Schema Plus Views gem。

在Rails中创建了一个SQL视图

为了干掉我的SQL视图模型,我为所有SQL视图模型创建了一个超类。

class SqlView < ActiveRecord::Base
  self.abstract_class = true
  self.primary_key = :id
  after_initialize :readonly!
end

然后我继承了SQL视图

class ChallengeView < SqlView

end

问题是self.primary_key不是继承的。

irb(main):008:0> c = ChallengeView.find(1)
ActiveRecord::UnknownPrimaryKey: Unknown primary key for table challenge_views in model ChallengeView.

如果我将它添加到模型中,它可以正常工作。

class ChallengeView < SqlView
  self.primary_key = :id
end


irb(main):001:0> c = ChallengeView.find(1)
  ChallengeView Load (2.7ms)  SELECT  "challenge_views".* FROM  "challenge_views" WHERE "challenge_views"."id" = $1 LIMIT 1  [["id", 1]]
=> #<ChallengeView id: 1, organizer_id: 1, challenge: ....

修改

根据Rails文档,它可以被覆盖。

http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html

1 个答案:

答案 0 :(得分:2)

为什么不将配置包含为模块?

module SqlView
  def included(base)
    base.module_eval do
      self.abstract_class = true
      self.primary_key = :id
      after_initialize :readonly!
    end
  end
end

class ChallengeView < ActiveRecord::Base
  include SqlView
end