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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With