ruby-on-rails – 将回形针从回形针返回给json
发布时间:2020-12-17 03:37:50 所属栏目:百科 来源:网络整理
导读:我有一个rails应用程序,它包含一个CMS系统,我用它来从城市到我的数据库输入景点.我正在使用回形针将图像上传到亚马逊s3.一切都很好.现在我想要ios应用程序将使用的json文件包含在s3中上传的图像的URL.我在这里看到了一些答案,但我似乎无法使我的代码工作.我
我有一个rails应用程序,它包含一个CMS系统,我用它来从城市到我的数据库输入景点.我正在使用回形针将图像上传到亚马逊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 谁能帮帮我吗? 解决方法
在引用您链接到(
How can I get url for paperclip image in to_json)的SO问题时,为了使图像正确呈现,您需要某些元素
你遇到的问题是Paperclip的图像方法实际上是一个ActiveRecord对象,因此你不能只是在JSON请求中渲染它而不做其他的东西 _url方法 该过程最重要的部分是在资产模型中定义“_url”方法.这基本上调用了Paperclip的.url函数,允许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]) 由于您的资产模型是地方的关联,因此可能无法立即生效.然而,它肯定是在正确的方向,因为我记得自己做这件事 这里要注意的重要一点是,你实际上是通过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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |