繁体   English   中英

Rails:在视图上下文之外使用JBuilder视图

[英]Rails: Using JBuilder views outside of the view context

我目前正在将ActiveModelSeralizer切换到JBuilder来渲染jsons。 我想知道,使用ActiveModelSeralizer我可以做类似的事情:

text_content = UserSeralizer.new(user, :root => false)

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

我有app/view/api/v1/users/_user.json.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

  json = ActionController::Base.new.view_context.render(partial: "api/v1/users/user", locals: {user: @user})

“我在app / view / api / v1 / users / _user.json.jbuilder里面有一个部分视图,无论如何将该部分呈现为变量吗?”

怎么样

json.partial! 'api/v1/users', users: @users.all

这将渲染部分并使用内容@ users.all创建一个新变量users

在我使用的控制器中

渲染json:无论如何

例:

  1. items_controller.rb (顺便说一下,我使用的是MongoDB):
 def show render json: @item end 
  1. http://localhost:3000/items/他用JSON回复我: 在此输入图像描述

我没有使用过任何观点

试试这段代码:

text_content = json.(user, :id, :name, :published_at)

jbuilder Railscasts

jbuilder响应为数组

对于渲染,您可以使用此代码:

json.partial! 'api/v1/users', users: @users.all

json呈现部分

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM