微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Rails:在视图上下文之外使用JBuilder视图

我目前正在将ActiveModelSeralizer切换到JBuilder来渲染jsons.我想知道,使用ActiveModelSeralizer我可以做类似的事情:
text_content = UserSeralizer.new(user,:root => false)

并在名为text_content的变量中接收json字符串.既然我正在转离ActiveModelSeralizer,那么无论如何都要使用JBuilder进行上述操作吗?

我有app / view / api / v1 / users / _user.json.jbuilder里面的部分视图是否有将部分渲染为变量?

谢谢

解决方法

是的你可以.只需使用Jbuilder.encode方法
# somewhere in User model

def display_to_json
  Jbuilder.encode do |json|
    json.name name
    json.location display_location
    json.description description
    json.work_experience work_experience
  end
end

并使用它:

<!-- somewhere in view,just for example -->
<div ng-init="user = <%= @user.display_to_json %>"></div>

注意:类名是Jbuilder,而不是JBuilder.

原文地址:https://www.jb51.cc/ruby/270954.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐