在 html.erb 我有:
<%= ContactDescribe.where(["contact_describe_id = ?", "12"]).limit(1).pluck(:borrower_or_lender_text) %>
该字段已成功检索。但返回一个数组元素。我需要学习如何将该元素转换为字符串。
在 html.erb 我有:
<%= ContactDescribe.where(["contact_describe_id = ?", "12"]).limit(1).pluck(:borrower_or_lender_text) %>
该字段已成功检索。但返回一个数组元素。我需要学习如何将该元素转换为字符串。
除了 Deepak 的回答,您还可以将其Array
转换为“Sentence”字符串
<%= ContactDescribe.where(contact_describe_id: 12).limit(1).pluck(:borrower_or_lender_text).to_sentence %>
正如 TheChamp 所指出的,最佳实践是已经“准备”视图中所需的值作为来自控制器的实例变量。请参阅我推荐的重构
# controller
def YOUR_ACTION_NAME
@contact_describe = ContactDescribe.where(contact_describe_id: 12).first
end
# view
<%= @contact_describe.borrower_or_lender_text %>
注意:除非您有其他需要的理由,否则您甚至不再需要采摘limit(1)
这里的问题是where
返回一个集合——类似于数组的东西,只是在 ActiveRecord 中——不管你设置了什么限制。检索您将使用的信息,.first
或者[0]
因为您始终只返回一个对象。
但是,因为您正在寻找一个特定的ContactDescribe
对象。改为这样做:
ContactDescribe.find_by(contact_describe_id: 12).borrower_or_lender
此外,您应该在代码中改进两件事。
1:逻辑应该进入控制器或模型。视图仅用于显示对象。
2:这个contact_describe_id
领域怎么了?为什么不调用它id
。似乎是多余的。不是user.id
更方便user.user_id
吗?
你可以利用join
<%= ContactDescribe.where(contact_describe_id: 12).limit(1).pluck(:borrower_or_lender_text).join(',') %>