0

モデルをjsonとしてフォーマットしているファイル(show.json.erb)があります。私のアプリでは、プロジェクトには多くのステップと多くの画像があり、ステップには多くの画像があります。

「条件」を使用して実行しようとしているプロジェクトのデフォルト イメージのみを含めることができるようにしたいと考えています。ただし、条件を無視して、プロジェクトに関連付けられたすべての画像を投稿しているようです。適切な画像のみを含めるにはどうすればよいですか?

"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 %>
4

1 に答える 1

2

Projects モデルに image_path というメソッドを作成することで、この問題を解決しました。

(3種類の画像を返すメソッドが必要でした)

  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"
      },
...]

これが他の誰かに役立つことを願っています!

于 2013-07-09T03:18:32.037 に答える