加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – 如何从表记录的子集创建Rails模型

发布时间:2020-12-17 02:53:52 所属栏目:百科 来源:网络整理
导读:我正在尝试创建几个模型,所有模型都来自同一个表.如何限制每个模型中的表记录?在你告诉我改变我的数据结构之前,这是一个报告应用程序,它从一个我无法控制的预先存在的后备数据库中提取. 我的表看起来像: Vehicle_Tableid vehicle_type name---------------
我正在尝试创建几个模型,所有模型都来自同一个表.如何限制每个模型中的表记录?在你告诉我改变我的数据结构之前,这是一个报告应用程序,它从一个我无法控制的预先存在的后备数据库中提取.

我的表看起来像:

Vehicle_Table
id vehicle_type name
--------------------
1  Car          Foo
2  Car          Bar
3  Motorcycle   Baz
4  Car          Barf

我想为汽车和摩托车建造模型,如:

class Car < ActiveRecord::Base
  set_table_name 'Vehicle_Table'

end

class Motorcycle < ActiveRecord::Base
  set_table_name 'Vehicle_Table'

end

但是我不知道怎么说,“嘿活跃唱片,我只想要记录里面的车辆类型=摩托车模型中的摩托车.”

我确信这很明显,但我的所有Google搜索都会返回模型中FIND子集的方式,而不是将模型限制为特定的记录子集.

解决方法

这称为单表继承(STI).

如果表中有一个名为type的列,它可能会自动运行.但是您可以更改Rails使用的列名称来区分类型.

http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Single table inheritance

Active Record allows inheritance by storing the name of the class in a column that by default is named “type” (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this:

class Company < ActiveRecord::Base; end
class Firm < Company; end
class Client < Company; end
class PriorityClient < Client; end

When you do Firm.create(:name => “37signals”),this record will be saved in the companies table with type = “Firm”. You can then fetch this row again using Company.where(:name => ’37signals’).first and it will return a Firm object.

所以,试试这个代码吧

class Car < ActiveRecord::Base
  set_table_name 'Vehicle_Table'
  self.inheritance_column = :vehicle_type
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读