json - Rails: Calling Model methods in to_json(:methods => [:model_method]) -
i've defined 2 methods in model image_url
& thumb_url
to absolute url
of images , thumbs , calling them in controller .to_json()
method.
when view json
response shows image_url
not thumb_url
please guide me doing wrong here.
model :
class post < activerecord::base include rails.application.routes.url_helpers validates :image, presence: true has_attached_file :image, styles: { :medium => "640x", thumb: "100x100#" } # # means crop image validates_attachment_content_type :image, :content_type => /\aimage\/.*\z/ def image_url relative_path = image.url(:medium) self.add_host_prefix relative_path end def thumb_url relative_path = image.url(:thumb) self.add_host_prefix relative_path end def add_host_prefix(url) uri.join(root_url, url).to_s end end
controller :
class api::imagescontroller < applicationcontroller def index @posts = post.all.order(id: :desc) paginated_records = @posts.paginate(:page => params[:page], :per_page => params[:per_page]) @posts = with_pagination_info( paginated_records ) render :json => @posts.to_json(:methods => [:thumb_url], :methods =>[:image_url]) end end
here json response:
"data": [{ "id": 23, "caption": "world top view", "created_at": "2015-09-17t14:10:57.278z", "updated_at": "2015-09-17t14:10:57.278z", "image_file_name": "world.topo.bathy.200401.3x21600x10800.jpg", "image_content_type": "image/jpeg", "image_file_size": 29698041, "image_updated_at": "2015-09-17t14:10:36.975z", "image_url": "http://localhost:3000/system/posts/images/000/000/023/medium/world.topo.bathy.200401.3x21600x10800.jpg?1442499036"}
you can't pass 2 :methods
keys hash, last key used. remember key hash has unique. if want mulitiple methods, should do...
render :json => @posts.to_json(:methods => [:thumb_url, :image_url])
Comments
Post a Comment