jbuilder icon indicating copy to clipboard operation
jbuilder copied to clipboard

person.to_json use partial /views/models/_models.json.jbuilder

Open create-marcel opened this issue 12 years ago • 5 comments

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

create-marcel avatar Mar 27 '14 13:03 create-marcel

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

rwz avatar Mar 29 '14 01:03 rwz

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

create-marcel avatar Mar 29 '14 20:03 create-marcel

@rwz Is there a way to render a jbuilder template to a json object (a ruby hash) instead?

phuongnd08 avatar Apr 09 '14 13:04 phuongnd08

JSON.parse(render("your/jbuilder/template"))

rwz avatar Apr 09 '14 13:04 rwz

Thanks. I'm using JSON.parse and tilt-jbuilder now.

phuongnd08 avatar Apr 09 '14 13:04 phuongnd08