Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails:在json中调用模型方法(:methods=>;[:Model\u method])_Ruby On Rails_Json_Activerecord - Fatal编程技术网

Ruby on rails Rails:在json中调用模型方法(:methods=>;[:Model\u method])

Ruby on rails Rails:在json中调用模型方法(:methods=>;[:Model\u method]),ruby-on-rails,json,activerecord,Ruby On Rails,Json,Activerecord,我在Modelimage\u-url和thumb\u-url中定义了两种方法来获取图像和拇指的绝对url 并在controller.to_json()方法中调用它们 当我查看Json响应时,它只显示image\u url而不是thumb\u url 请告诉我我做错了什么 型号: class Post < ActiveRecord::Base include Rails.application.routes.url_helpers validates :image, prese

我在Model
image\u-url
thumb\u-url
中定义了两种方法来获取图像和拇指的绝对
url
并在controller
.to_json()
方法中调用它们

当我查看
Json
响应时,它只显示
image\u url
而不是
thumb\u url
请告诉我我做错了什么

型号:

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 the 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
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
"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"}

不能将两个
:方法
键传递到哈希中,只使用最后一个键。请记住,散列的键必须是唯一的。如果你想要多种方法,你应该

render :json => @posts.to_json(:methods => [:thumb_url, :image_url])