我有一个包含CMS系统的rails应用程序,该系统用于将景点从城市输入到数据库。我正在使用回形针将图像上传到亚马逊s3。一切正常。现在,我想让ios应用程序使用的json文件包含s3中上传的图像的url 。我在这里看到了一些答案,但似乎无法使我的代码正常工作。我有这个。
放置模型
attr_accessible :assets_attributes, :asset
has_many :assets
accepts_nested_attributes_for :assets, :allow_destroy => true
def avatar_url
assets.map(&:asset_url)
end
资产模型
class Asset < ActiveRecord::Base
attr_accessible :asset_content_type, :asset_file_name, :asset_file_size, :asset_updated_at, :place_id, :asset
belongs_to :place
has_attached_file :asset
validates_attachment :asset, :presence => true,
:content_type => { :content_type => ['image/jpeg', 'image/png'] },
:size => { :in => 0..1.megabytes }
def asset_url
asset.url(:original)
end
end
查看代码
<%= f.fields_for :assets do |asset_fields| %>
<% if asset_fields.object.new_record? %>
<p>
<%= asset_fields.file_field :asset %>
</p>
<% end %>
<% end %>
<br/>
<%= f.fields_for :assets do |asset_fields| %>
<% unless asset_fields.object.new_record? %>
<%= link_to image_tag(asset_fields.object.asset.url(:original), :class => "style_image"), (asset_fields.object.asset.url(:original)) %>
<%= asset_fields.check_box :_destroy %>
<% end %>
<% end %>
位置控制器
def index
@places = Place.all
render :json => @places.to_json(:methods => [:avatar_url])
end
谁能帮帮我吗?
关于链接到的SO问题(如何在to_json中获取回形针图像的url),需要一些元素才能使图像正确呈现
您遇到的问题是Paperclip的image
方法实际上是一个ActiveRecord对象,因此,您不能不做其他事情就只能在JSON请求中呈现它
该_url
方法
该过程中最重要的部分是在asset
模型中定义“ _url”方法。这基本上调用了.url
Paperclip函数,允许JSON快速创建图像的所需URL(图像的URL不是ActiveRecord对象,因此可以通过JSON发送)
根据所引用的SO问题,您应该将此操作放入模型中:
#app/models/asset.rb
def asset_url
asset.url(:medium)
end
现在,当您在控制器中呈现JSON请求时,可以使用以下类型的设置:
#app/controllers/places_controller.rb
render :json => @places.to_json(:methods => [:asset_url])
由于您的asset
模型是的关联places
,因此可能无法立即生效。但是,这绝对是正确的方向,因为我记得自己做的这件事
这里要注意的重要一点是,您实际上是通过JSON传递图像的裸露“ URL”,而不是图像对象本身
更新资料
这是我们制作的视频会议演示应用程序中的一个示例:
#app/controllers/profiles_controller.rb
def update
@profile = User.find(current_user.id)
@profile.profile.update(upload_params)
respond_to do |format|
format.html { render :nothing => true }
format.js { render :partial => 'profiles/update.js' }
format.json { render :json => @profile.profile.as_json(:only => [:id, :avatar], :methods => [:avatar_url])
}
end
end
#app/models/profile.rb
def avatar_url
avatar.url(:original)
end
因此,对于您来说,我会尝试这样做:
def index
@places = Place.all
render :json => @places.assets.as_json(:only => [:id, :asset], :methods => [:asset_url])
end
您也可以尝试如下操作:
#app/models/profile.rb
def avatar_url
self.asset.avatar.url(:original)
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句