使用带有条件语句的Rails as_json

时间:2013-07-08 22:18:34

标签: ruby-on-rails json

我有一个文件(show.json.erb),我将模型格式化为json。在我的应用程序中,项目有许多步骤和许多图像,步骤有很多图像。

我希望能够仅包含项目的默认图像,我正在尝试使用“条件”。但是,它似乎忽略了条件并发布了与项目相关的所有图像。如何仅包含正确的图像?

"projects":
<%= JSON.pretty_generate(@projects.order("updated_at DESC").as_json(only: [:title, :id, 
    :built, :updated_at], include: {images: {only: [:image_path], 
    :conditions=>['Step.find(image.step_id).name.eql? "Project Overview"', true] }  
})).html_safe %>

1 个答案:

答案 0 :(得分:2)

我通过在我的Projects模型中创建一个名为image_path的方法解决了这个问题:

(我需要返回三种图像的方法)

  def image_path
    images = Hash.new
    if first_step.images.present?
        images["url"] = first_step.first_image.image_path_url    
        images["preview"] = first_step.first_image.image_path_url(:preview) 
        images["thumbnail"] = first_step.first_image.image_path_url(:thumb) 
    end
    return images
  end

然后我编辑了我的JSON,看起来像这样:

   "projects":
        <%= JSON.pretty_generate(@projects.order("updated_at DESC").as_json(only: [:title, :id, :built], :methods=> [:image_path, :updated_at_formatted])).html_safe %>

这在我的网站上呈现如下:

    "projects":
                [
      {
        "built": true,
        "id": 115,
        "title": "Video Test",
        "image_path": {
          "url": "https://s3.amazonaws.com/...",
          "preview": "https://s3.amazonaws.com/...",
          "thumbnail": "https://s3.amazonaws.com/..."
        },
        "updated_at_formatted": "07/08/2013 10:31:19"
      },
...]

希望这有助于其他人!