我有一个汽车模型和图片模型 . 车 has_many :pictures 和图片 belongs_to :car

我正在使用Carrierwave保存图片,效果很好 .

在我构建API时,我想返回完整的图片路径 .

我已经覆盖了Car模型的as_json方法,如下所示;

def as_json(options={})
  super(:except => [:hourly_price, :hourly_checkin, :hourly_weekend, :max_h_p, :hourly_price_range_id, :created_at, :updated_at, :gid_id],
        :include => {
          :pictures => {:except => [:id, :name, :created_at, :updated_at, :car_id]})
end

在控制台上,如果我写 Car.last.pictures.image_url(:slider).to_s . 这给了我完整的路径 . 但是当API返回json时,我只能看到图像的名称而不是完整路径 .

我想我也需要覆盖图片模型中的一些功能..

我试过这个,但到目前为止还不行 .

pictures.rb
def to_json(options = nil)
    params = {id: self.id, name: self.name, car_id: self.car_id, position: self.position, image: self.image.url}
    ActiveSupport::JSON.encode(params, options)
end

EDIT

我在picture.rb上覆盖了as_json,如下所示;

def as_json(options={})
    super(only: [:id, :name, :car_id, :position],
        methods: [:image]
    )   
end

def image
    self.image_url(:slider).to_s
end

但它给出了错误; NoMethodError (undefined method image_url'代表#):`

但是,当我键入 Car.last.pictures.last.image_url(:slider).to_s 时,它在控制台上工作