gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:11:57 26 4
gpt4 key购买 nike

我正在尝试创建几个模型,这些模型都从同一个表中提取。如何限制每个模型中的表记录?在您告诉我更改数据结构之前,这是一个报告应用程序,它从我无法控制的预先存在的支持数据库中提取。

我的 table 看起来像:

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

但我不知道怎么说,“嘿,Active Record,我只想要摩托车模型中车辆类型 = 摩托车的记录。”

我确信这很明显,但我所有的 Google 搜索都返回在模型中查找子集的方法,而不是将模型限制为特定的记录子集。

最佳答案

这称为单表继承 (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

关于ruby-on-rails-3 - 如何从表记录的子集创建 Rails 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9285970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com