加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:调用to_json中的模型方法(:methods =&

发布时间:2020-12-17 03:18:20 所属栏目:百科 来源:网络整理
导读:我在模型image_url中定义了两种方法. thumb_urlto获取图像和拇指的绝对URL 并在控制器.to_json()方法中调用它们. 当我查看Json响应时,它只显示image_url而不是thumb_url 请指导我在这里做错了什么. 型号: class Post ActiveRecord::Base include Rails.appl
我在模型image_url&中定义了两种方法. thumb_urlto获取图像和拇指的绝对URL
并在控制器.to_json()方法中调用它们.

当我查看Json响应时,它只显示image_url而不是thumb_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

这是我的Json回应:

"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])

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读