I have a Ruby on Rails App that uses jbuilder. I am using jbuilder to help render json responses. Is there a way assign the jbuilder partial to a variable without rendering the result? I have been trying to do something like below, but I am getting this undefined method 'key' for nil:NilClass
error. It seems I am not correctly passing the users model to the user.json.jbuilder
Can anyone offer any help?
context = ActionController::Base.new.view_context
user_json = JbuilderTemplate.new(context) do |json|
json.partial! "/users_api/user.json.jbuilder", user: user
end.target!
You can return the JSON from Jbuilder directly with JbuilderTemplate
combined with .target!
, but the filename is required to start with an underscore. Starting the filename with and underscore denotes it as a partial which means it can't be rendered directly.
References (How to render Jbuidler partials inside a model?, Missing partial in rails)
Return JSON directly (calls _user.json.jbuilder
)
context = ActionController::Base.new.view_context
user_json = JbuilderTemplate.new(context) do |json|
json.partial! "/users_api/user.json.jbuilder", user: user
end.target!
Render JSON (calls user.json.jbuilder
which call _user.json.jbuilder
)
render "/users_api/user.json.jbuilder"
user.json.jbuilder
json.partial! "/users_api/user.json.jbuilder", user: @user
_user.json.jbuilder
json.email user.email
json.name user.name