ruby-on-rails - rails : Calling Model methods in to_json(:methods => [:model_method])

标签 ruby-on-rails json activerecord

我在 Model image_url 中定义了两个方法& thumb_url获得绝对url图像和拇指
并在 Controller 中调用它们 .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

Controller :
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"}

最佳答案

你不能通过两个 :methods键进入散列,只使用最后一个键。请记住,散列的键必须是唯一的。如果你想要多种方法,你应该做...

render :json => @posts.to_json(:methods => [:thumb_url, :image_url])

关于ruby-on-rails - rails : Calling Model methods in to_json(:methods => [:model_method]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32689407/

相关文章:

ruby-on-rails - Ruby - 两个集合的交集,它们是两个不同对象的属性

ruby-on-rails - 通过 Rails ActiveRecord Association 调用类方法

ruby-on-rails - 使用不带轮胎的自定义名称创建轮胎的索引:import

html - 我想更改我的导航栏字体和颜色

ruby-on-rails - 模型关联问题

mysql - 作为 HTTP 响应的 JSON 对象集 - NodeJS

java - 使用 Gson 反序列化有时是字符串有时是对象

json - 如何使用NSJSONSerialization类引用读取JSON文件?

sql - Rails 相关子查询同表

css - 预加载 css Sprite