抽象 ActiveRecord 属性
在不进一步规范化数据库的情况下抽象 ActiveRecord 属性的最佳方法是什么?
例如,假设一个名为 addresses
的数据库表,其中包含一个 zip_code
列和一个确定邮政编码是否有效的方法:
class Address < ActiveRecord::Base
def zip_code_valid?
..
end
end
我希望拥有:
class Address < ActiveRecord::Base
..
end
class ZipCode
def valid?
..
end
end
当我执行Address.find(1).zip_code
,它返回一个 ZipCode
与一个字符串。我不想通过创建名为 zip_codes
的表来标准化数据库。这个例子是假设的,我目前没有现实世界的例子;我只是想知道我怎样才能做到这一点。
谢谢。
What is the best way to abstract an ActiveRecord attribute without further normalizing the database?
For example, let's assume a database table named addresses
with a column zip_code
and a method to determine if the zip code is valid:
class Address < ActiveRecord::Base
def zip_code_valid?
..
end
end
I would prefer to have:
class Address < ActiveRecord::Base
..
end
class ZipCode
def valid?
..
end
end
and when I execute Address.find(1).zip_code
, it returns a ZipCode
vs. a string. I would prefer not to normalize the database by creating a table called zip_codes
. The example is hypothetical, and I currently do not have a real world example of this; I simply want to know how I could potentially do this.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您所讨论的,我不确定您为什么要对 ZipCode 执行此操作,但要回答您的问题,您应该考虑使用 Rails 聚合。
这是文档:
http://api.rubyonrails.org/classes/ActiveRecord/Aggregations /ClassMethods.html
如果您对想要完成的事情有具体问题,请告诉我,我可以尝试回答这些具体问题。
I'm not sure why you'd want to do this for
ZipCode
as you discussed, but to answer your question, you should consider using Rails Aggregations.Here's the documentation :
http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html
If you have specific questions about things you want to accomplish, let me know and I can try to answer those specific questions.
如果您不打算对街道、门牌号、城市等执行相同的操作,我认为将邮政编码抽象到类中是没有意义的。您已经将其作为地址表中的单独列,因此将其存储在自己的类中是没有意义的(从 ActiveRecord 的角度来看)。或者,如果您将邮政编码存储在自己的表(以及类)中,您会获得什么?在我看来,如果单个属性作为其当前所在的聚合的一部分有意义,那么将其保留在单独的类/表中就太过分了。
I don't think abstracting the zip code out into a class makes sense if you're not going to do the same with the street, house number, city, etc. You already have it as a separate column in the Address table, so it doesn't make sense to store it in its own class (from an ActiveRecord point of view). Alternatively, if you store zip codes in their own table (and hence class), what are you gaining? In my opinion it's going too far to keep a single attribute in a separate class/table if it makes sense as to be part of the aggregate that it's currently in.