person.to_json use partial /views/models/_models.json.jbuilder
how could i overwrite the to_json method of a model that i get a json using the /views/_model.json.jbuilder
i don't want to copy the partials content into the model. wouldnt be DRY
This is a terrible idea and you should never do that.
However, if you think you know what you're doing, you can use following code to make it work:
class MyModel < AR::Base
def to_json
ApplicationController.new.view_context.render(
partial: to_partial_path,
locals: { self.class.model_name.element => self },
formats: [:json],
handlers: [:jbuilder]
)
end
end
thx well i want to be able to save the json to a file beside accessing it live in the controller (zipped, standalone angular application) and as i want to define how the json looks like only once, the idea doesnt sound too terrible
def as_json_to_file
klass_param = self.class.name.pluralize.underscore
path = "public/Package/charts/"+klass_param+"/"
c = ActionController::Base.new
str = c.render_to_string(template: klass_param+'/_page.json.jbuilder', locals: {:page => self, relative_paths: true})
Dir.mkdir(Rails.root.join(path)) unless File.exists?(Rails.root.join(path))
File.open(Rails.root.join(path + self.id.to_s + ".json"), 'w') { |f| f.write(str) }
end
@rwz Is there a way to render a jbuilder template to a json object (a ruby hash) instead?
JSON.parse(render("your/jbuilder/template"))
Thanks. I'm using JSON.parse and tilt-jbuilder now.