11

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

Bill
  • 3,059
  • 3
  • 31
  • 47

5 Answers5

27

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.

Tom Chen
  • 1,489
  • 2
  • 12
  • 17
  • 3
    This doesn't answer the posted question. It redefines a json representation inside the block and does **not** make use of a present jbuilder template. – Ekkstein Mar 22 '19 at 13:14
5
  json = ActionController::Base.new.view_context.render(partial: "api/v1/users/user", locals: {user: @user})
Jake
  • 251
  • 4
  • 4
0

"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

Joseph Sawyer
  • 463
  • 3
  • 11
0

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: enter image description here

I have not used any views

skozz
  • 2,662
  • 3
  • 26
  • 37
0

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

Community
  • 1
  • 1
Mohamed Yakout
  • 2,868
  • 1
  • 25
  • 45