Reputation: 4715
I want to save json into a database field for later use. How should I go about that with Jbuilder?
I want to use an item's show template, passing in the object, @item to save the output for that Item into the database for later use.
I got some output with the following code:
view_paths = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
av_helper = ActionView::Base.new view_paths
include Rails.application.routes.url_helpers
@job = Job.find(239)
output = av_helper.render(file: '/api/jobs/show.jbuilder', locals: {:@job => @job})
How can I render the saved json directly from the controller?
Add this for the action code in the controller
def show
@job = Job.find(params[:id])
render :inline => @job.json_output
end
Upvotes: 0
Views: 418
Reputation: 102046
render_to_string
Raw rendering of a template to a string.
It is similar to render, except that it does not set the response_body and it should be guaranteed to always return a string.
Also if you're doing it from a controller there you can just use the controller to render it:
class JobsController
def create
@job = Job.new(item_params) do |job|
job.my_json_attribute = render_to_string(:show, locals: { :@job => job})
end
if @job.save
redirect_to @job
else
render :new
end
end
end
But this seems like a pretty overcomplicated and flawed way to handle something that can be done with e-tag caching and a reverse proxy or even low level caching. Especially since you would have to repeat the logic when updating the item.
Upvotes: 0