Rails 6 - 将渲染内容从 erb 模板写入模型属性
Rails 6 - write rendered content from erb template to model attribute
我有一个消息模型,它是一种粗略的消息传递系统。 Message 模型有一个名为 :body 的文本属性,它显然以 html 格式存储消息的内容。
我想做的是使用其他模型中的回调触发一条新消息,并使用 erb 模板中呈现的内容填充 :body 属性。
例如:
Class Assignment < ApplicationRecord
belongs_to :user
after_create :send_message_to_user
def send_message_to_user
Message.create!(recipient: user, body: ("html content here I guess"))
end
end
在 rails 中如何做到这一点?
我想你可以这样使用 render
:
def send_message_to_user
Message.create!(
recipient: user,
body: ApplicationController.render 'templates/name',
)
end
受此答案启发:
我有一个消息模型,它是一种粗略的消息传递系统。 Message 模型有一个名为 :body 的文本属性,它显然以 html 格式存储消息的内容。
我想做的是使用其他模型中的回调触发一条新消息,并使用 erb 模板中呈现的内容填充 :body 属性。
例如:
Class Assignment < ApplicationRecord
belongs_to :user
after_create :send_message_to_user
def send_message_to_user
Message.create!(recipient: user, body: ("html content here I guess"))
end
end
在 rails 中如何做到这一点?
我想你可以这样使用 render
:
def send_message_to_user
Message.create!(
recipient: user,
body: ApplicationController.render 'templates/name',
)
end
受此答案启发: