简体   繁体   中英

Rails: Using JBuilder views outside of the view context

I am currently switching ActiveModelSeralizer to JBuilder for rendering jsons. I was wondering, with ActiveModelSeralizer I can do something like:

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

And receieve the json string in the variable called text_content . Now that I am switching away from ActiveModelSeralizer, is there anyway to do the above with JBuilder?

I have a view partial inside of app/view/api/v1/users/_user.json.jbuilder Is there anyway to render that partial into a variable?

Thanks

Yes, you can. Just use Jbuilder.encode method:

# 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

and use it:

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

Notice : The class name is Jbuilder , not JBuilder .

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

"I have a view partial inside of app/view/api/v1/users/_user.json.jbuilder Is there anyway to render that partial into a variable?"

How about

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

This will render the partial and create a new variable, users, with the contents @users.all

In the Controller I used

render json: whatever

Example:

  1. In items_controller.rb (btw I used MongoDB):
 def show render json: @item end 
  1. And http://localhost:3000/items/ he replies me with the JSON: 在此输入图像描述

I have not used any views

Try this code:

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

jbuilder Railscasts

jbuilder response as array

For Render you can use this code:

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

json render for partial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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