我正在尝试创建一个助手,该助手将格式化5列(add1,add2,add3,add4,add5)中的地址,以便压缩所有null并在屏幕上如此显示
Add1,
Add3,
Add4,
Add5
(由于没有添加,因此跳过了添加2)
我创建了以下帮助程序来汇编和跳过所有null,但无法引入新的换行符。有什么想法吗?
def delivery_address(customer)
@customer = Customer.find(customer.id)
if @customer.del_address1.blank?
deladdress = "No Delivery Address"
else
deladdress = @customer.del_address1
deladdress = deladdress + "</br>"
if customer.del_address2.blank?
else
deladdress = deladdress + @customer.del_address2 + ","
end
if @customer.del_address3.blank?
else
deladdress = deladdress + @customer.del_address3 + ","
end
if @customer.del_address4.blank?
else
deladdress = deladdress + @customer.del_address4 + ","
end
if @customer.del_address5.blank?
else
deladdress = deladdress + @customer.del_address5
end
end
end
答案 0 :(得分:0)
def delivery_address(customer)
@customer = Customer.find(customer.id)
return "No Delivery Address" if @customer.del_address1.blank?
[
@customer.del_address1,
@customer.del_address2,
@customer.del_address3,
@customer.del_address4,
@customer.del_address5
].reject(&:blank?).join(",\n")
end
您可以将所有值放入数组中,然后删除所有空白值,而不是编写5条if
语句。
请注意,我的代码是基于您的代码,但与您的问题要求不完全相同
它将压缩所有空值
空字符串也被视为blank?
(但"" != nil
)。因此,此方法也会跳过这些值。
如果您只想忽略nil
的值,但保留空字符串,则将reject(&:blank?)
替换为compact
。
答案 1 :(得分:0)
一个重要的建议:您不应在视图助手中进行任何数据库查询。这仅应在控制器中完成。活动记录应该已经传递到辅助函数中。所以这行
@customer = Customer.find(customer.id)
可以删除。
def delivery_address(customer)
# Use a guard clause, this reduces if nesting
return 'No Delivery Address' if customer.del_address1.blank?
# Collect all parts
parts = [customer.del_address1, customer.del_address2, customer.del_address3, customer.del_address4, customer.del_address5]
# Remove all empty parts.
# Using a bang method is lighter on memory allocation
# and will speed up performance.
parts.reject!(&:blank?)
parts.join('<br/>').html_safe
end