如何从表记录的子集创建 Rails 模型
我正在尝试创建几个模型,这些模型都来自同一个表。如何限制每个模型的表记录?在您告诉我更改数据结构之前,这是一个报告应用程序,它是从我无法控制的预先存在的支持数据库中提取的。
我的表格看起来像这样:
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,我只想要摩托车模型中 Vehicle_type = 摩托车的记录。”
我确信这是显而易见的,但是我所有的 Google 搜索都会返回在模型中查找子集的方法,而不是将模型限制为特定的记录子集。
I am trying to create several models that all pull from the same table. How do I limit the table records in each model? And before you tell me to change my data structure, this is a reporting application that is pulling from a preexisting backing DB over which I have no control.
My table looks something like:
Vehicle_Table
id vehicle_type name
--------------------
1 Car Foo
2 Car Bar
3 Motorcycle Baz
4 Car Barf
And I want to build models for Car and Motorcycle like:
class Car < ActiveRecord::Base
set_table_name 'Vehicle_Table'
end
and
class Motorcycle < ActiveRecord::Base
set_table_name 'Vehicle_Table'
end
But I have no idea how to say, "Hey Active Record, I only want records where vehicle_type = motorcycle in the motorcycle model."
I'm sure this is friggin' obvious, but all of my Google searches return ways to FIND subsets in a model rather than RESTRICT a model to a specific subset of records.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
上面发表了评论,但编辑能力有限。我遇到了这个确切的问题,并在其他地方找到了解决方案的后半部分。 STI 将允许您根据表中的列获取表的子集,但它将关闭类名以查找该类的记录。例如:
class Company < ActiveRecord::Base; end
class Client < Company; end
这将查看名为 Company 的表,查找名为“Type”的列中具有值“Client”的记录。
您可以通过执行以下操作来覆盖 STI 检查的列
class Company < ActiveRecord::Base
self.inheritance_column = :company_type
end
,但它仍然会查找包含“Client”的该列。您可以通过执行以下操作来覆盖它查找的值:
class Client < Company
def self.sti_name
1
end
end
现在,这将在 company_type 列中查找值为 1 的行。
对于 Rails-4.2,这几乎相同,但不需要类方法:
private
self.inheritance_column = :company_type
def sti_name
1
end
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
这称为单表继承 (STI)。
如果您的表中有一个名为
type
的列,它可能会自动工作。但是您可以更改 Rails 用于区分类型的列名称。http://api.rubyonrails.org/classes/ActiveRecord/Base.html
所以,试试这个代码
This is called Single Table Inheritance (STI).
If you had a column named
type
in your table, it would likely work automatically. But you can change this column name that Rails uses to tell types apart.http://api.rubyonrails.org/classes/ActiveRecord/Base.html
So, try this code