简体   繁体   English

在ActiveRecord :: Base子类中设置table_name

[英]Setting table_name in ActiveRecord::Base subclass

I have an abstract class: 我有一个抽象类:

class AbstractBrowsable < ActiveRecord::Base  
  self.abstract_class = true
  attr_accessible :heading
  [...]
  def get_following(count)
    AbstractBrowsable.where("heading > ?", self.heading).order('heading ASC').limit(count)
  end
end

It has some generic queries like the one above, so in the subclasses I need to set the table name eg 它具有一些类似于上面的查询,因此在子类中,我需要设置表名,例如

class Subject < AbstractBrowsable
  AbstractBrowsable.table_name = "subjects"
end

The ''only'' way I can get this to work is as shown above, ie AbstractBrowsable.table_name = "subjects" and not self.table_name = 'subjects' . 我可以使它工作的“唯一”方法如上所述,即AbstractBrowsable.table_name = "subjects"而不是self.table_name = 'subjects' This seems fishy to me, and my Google-Fu only turns up examples using self. 这对我来说似乎很可疑,而且我的Google-Fu仅使用self.来显示示例self. . Is this OK, or else what am I missing? 这样可以吗,否则我想念什么?

If you haven't guessed, I'm new to Ruby/Rails; 如果您还没猜到,我是Ruby / Rails的新手。 any help much appreciated. 任何帮助,不胜感激。 My Rails version is 3.2.13, and Ruby is 1.9.3. 我的Rails版本是3.2.13,而Ruby是1.9.3。

You should be using self unless you are trying to do STI, which case you'd need to not set abstract_class. 除非您尝试执行STI,否则应该使用self,在这种情况下,您无需设置abstract_class。

-- edit -- -编辑-

Based on what you described in your comment what you need is to build the functionality into module(s) and include them in your classes. 根据您在评论中描述的内容,您需要将功能构建到模块中,并将其包括在类中。 This is the purpose of modules in Ruby. 这是Ruby中模块的目的。

Recommend reading this: http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns 建议阅读以下内容:http: //37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns

Heres an example: 这里是一个例子:

module Browsable
  # Browsable methods
end

class Subject < ActiveRecord::Base
  include Browsable
  # 
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM