Paperclip:如何获取图片网址

时间:2015-06-02 10:01:17

标签: ruby-on-rails angularjs ruby-on-rails-4

我正在尝试将我的Rails服务器切换到AngularJS。到目前为止一切正常,但我不知道如何从Paperclip获取图像网址。

我收到的当前数据是:

{
  "id":52, 
  "name":"Samsung-Galaxy", 
  "cost":500, "brand":"Samsung", 
  "description":" Lorem Ipsum has been the industry's standard dummy text when ...", 
  "created_at":"2015-06-02T09:43:10.000Z", 
  "updated_at":"201509:43:10.000Z", 
  "avatar_file_name":"382727-samsung-galaxy-s-4-t-mobile.jpg", 
  "avatar_content_type":"image/jpeg", "avatar_file_size":20829, 
  "avatar_updated_at":"201502T09:43:10.000Z"
}

但如何在html页面上显示图像。

2 个答案:

答案 0 :(得分:1)

当您在模型中设置Paperclip时,如下所示:

class Phone
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end

您可以轻松地从Phone objectas described in the docs获取不同的图片。

@medium_avatar_url = Phone.first.avatar.url(:medium)

当然你不会通过实例变量发送它,而是将它实现到你的JSON响应中。

快速修复将是:

@product = Product.find(params[:id])
@product[:avatar_url] = @product.avatar.url(:medium)
respond_with(@product.as_json)

但我高度建议您查看the jbuilder gem,这会为您提供更多灵活性。 还有great Railscast让你去!

答案 1 :(得分:-2)

再添加一个 url 归档到JSON数据,将图像实际路径放在生成rails控制器上,就像这样......

@product = Product.find(params[:id])
@product[:url] = @product.avatar.url(:medium) //paperclip method
respond_with(@product.as_json)
相关问题