我想创建一个带有包含字符串插值的字符串属性的 Active Record 对象。
我的模型架构如下所示:
create_table "twilio_messages", force: true do |t|
t.string "name"
t.string "body"
t.datetime "created_at"
t.datetime "updated_at"
end
我使用 Active Admin 创建了这个模型的对象,如下所示:
=> #<TwilioMessage id: 5, name: "weekly_message", body: "\#{user.firstname} you're on the list for this week'...", created_at: "2014-05-29 22:24:36", updated_at: "2014-05-30 17:14:56">
问题是我为正文创建的字符串应该如下所示:
"#{user.firstname} you're on the list for this week's events! www.rsvip.biz/#events"
以便将 user.firstname 插入到字符串中,从而打印出用户名。
如何在数据库不自动尝试用“\”转义插值的情况下创建这种类型的记录?
最佳答案
你可以那样做,除非你想使用像 eval
这样讨厌的东西。字符串插值仅发生在字符串文字中,您不能说 s = '#{x}'
(不是单引号)然后在需要时替换 x
使用 s
。
有String#%
虽然:
str % arg → new_str
Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an
Array
orHash
containing the values to be substituted. SeeKernel::sprintf
for details of the format string.
所以你可以像这样使用body
:
m = TwilioMessage.create(
:body => "%{firstname} you're on the list for this week's events! www.rsvip.biz/#events",
...
)
然后,当您有了用户
时,像这样填写消息:
body = m.body % { :firstname => user.firstname }
当然,您必须知道 %{firstname}
在字符串中。如果您只有少量要插入的内容,那么您可以提供所有内容并让 %
挑选出需要的内容:
body = m.body % {
:firstname => user.firstname,
:lastname => user.lastname,
:email => user.email
}
甚至为您的用户添加一个方法:
def msg_vals
{
:firstname => self.firstname,
:lastname => self.lastname,
:email => self.email
}
end
然后说这样的话:
body = m.body % user.msg_vals
关于ruby-on-rails - 在模型的属性中包含字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23960084/