如何根据 Rails 中的条件为所有客户更新文本类型的列 4
How to update a column of type text for all customers based on a condition in Rails 4
我的 rails 应用程序中有一个客户模型和控制器。在我的客户列表索引页面中,我显示了所有具有搜索过滤器选项的客户,以根据他们的购买类型(销售、租赁、试用)显示客户。
@customers = Customer.where(customer_type: ["Sale","Lease","Trail"]).count
如果 count > 0
我想将他们的 customer_type
字段更新为大写形式 (Sale -> SALE , Lease -> LEASE, Trail - > TRAIL) @customers
集合中的所有客户。
如何以最优化的方式实现它?
@customers = Customer.where(customer_type: ["Sale","Lease","Trail"])
@customers.each do |customer|
customer.update_attribute(:customer_type, customer.customer_type.map(&:upcase))
end
检索到具有预期客户类型的客户后,我们遍历所有客户并将其属性更新为 customer_type
数组中所有字符串的大写版本。您不需要检查 count > 0
是否存在,因为如果 @customers
集合中没有项目,它不会循环。
customer.customer_type.map(&:upcase)
遍历客户 customer_type
数组中的每个字符串并对其应用 upcase
方法。
您可以在循环客户时使用ruby的upcase
方法。
@customers = Customer.where(customer_type: ["Sale","Lease","Trail"])
@customers.each do |customer|
customer_type = customer.customer_type.upcase
customer.update_attribute(:customer_type, customer_type)
end
如果您需要使用此查询更新多个文件,将 customer.update_attribute 更改为 customer.update_attributes。
就是这样。
如果有很多记录,在一个循环中初始化Active Record 对象不是那么有效。在这种情况下,您可以使用 ActiveRecord/Relation#update_all
Customer
.where(customer_type: ["Sale","Lease","Trail"])
.update_all("customer_type = UCASE(customer_type)")
这是给 MySql 的。对于 Oracle、Postgresql 和 Sql 服务器,使用 UPPER(column_name)
我的 rails 应用程序中有一个客户模型和控制器。在我的客户列表索引页面中,我显示了所有具有搜索过滤器选项的客户,以根据他们的购买类型(销售、租赁、试用)显示客户。
@customers = Customer.where(customer_type: ["Sale","Lease","Trail"]).count
如果 count > 0
我想将他们的 customer_type
字段更新为大写形式 (Sale -> SALE , Lease -> LEASE, Trail - > TRAIL) @customers
集合中的所有客户。
如何以最优化的方式实现它?
@customers = Customer.where(customer_type: ["Sale","Lease","Trail"])
@customers.each do |customer|
customer.update_attribute(:customer_type, customer.customer_type.map(&:upcase))
end
检索到具有预期客户类型的客户后,我们遍历所有客户并将其属性更新为 customer_type
数组中所有字符串的大写版本。您不需要检查 count > 0
是否存在,因为如果 @customers
集合中没有项目,它不会循环。
customer.customer_type.map(&:upcase)
遍历客户 customer_type
数组中的每个字符串并对其应用 upcase
方法。
您可以在循环客户时使用ruby的upcase
方法。
@customers = Customer.where(customer_type: ["Sale","Lease","Trail"])
@customers.each do |customer|
customer_type = customer.customer_type.upcase
customer.update_attribute(:customer_type, customer_type)
end
如果您需要使用此查询更新多个文件,将 customer.update_attribute 更改为 customer.update_attributes。 就是这样。
如果有很多记录,在一个循环中初始化Active Record 对象不是那么有效。在这种情况下,您可以使用 ActiveRecord/Relation#update_all
Customer
.where(customer_type: ["Sale","Lease","Trail"])
.update_all("customer_type = UCASE(customer_type)")
这是给 MySql 的。对于 Oracle、Postgresql 和 Sql 服务器,使用 UPPER(column_name)