Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 593
Bill Avatar asked Dec 23 '13 21:12

Bill


2 Answers

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.

like image 95
Tom Chen Avatar answered Nov 01 '22 00:11

Tom Chen


  json = ActionController::Base.new.view_context.render(partial: "api/v1/users/user", locals: {user: @user})
like image 24
Jake Avatar answered Oct 31 '22 23:10

Jake