加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:25:29 所属栏目:百科 来源:网络整理
导读:我目前正在将ActiveModelSeralizer切换到JBuilder来渲染jsons.我想知道,使用ActiveModelSeralizer我可以做类似的事情: text_content = UserSeralizer.new(user,:root = false) 并在名为text_content的变量中接收json字符串.既然我正在转离ActiveModelSerali
我目前正在将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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读