是否可以定义一个"仿真" RoR模型上的字段,定义为RDBMS中的函数?
例如,假设我有一个带有字段user_name
的模型。 user_name
始终采用" firstname lastname" (由空格分隔的两个字符串)。在mysql中,我可以使用SUBSTRING_INDEX(user_name, ' ', 1)
获得名字。
我想定义一个字段first_name
,让ActiveRecord总是使用适当的DB函数来读取(更重要的是,查询)字段,所以我可以这样做:
johns = User.where(:first_name => "John")
...而ActiveRecord会生成正确的SQL:
SELECT *, SUBSTRING_INDEX(user_name, ' ', 1) AS first_name
FROM users
WHERE SUBSTRING_INDEX(user_name, ' ', 1) = "John";
答案 0 :(得分:0)
你可以拥有一个ActiveRecord scope来完成那个
scope :first_name ->(x) { where("SUBSTRING_INDEX(?, ' ', 1) as first_name", x) }
将为您的AR模型提供所需的功能
johns = User.first_name("John")
更新
我们也可以通过简单的方法
拥有自定义属性读取器def first_name
user_name.split(" ").first
end
或者如果我们想要通过价值对象
更复杂和可扩展的东西def first_name
FirstName.new(self)
end
其中FirstName
类似于以下内容
class FirstName
def initialize(user)
self.first_name = user_name.a_production_method
...
# other attributes here
end
def get_first_name
first_name
end
# extra functionality here
end