0

Rails、Mongoid、搬送波を使用しています。

これが私が使用しているコードです。

page.rb

class Page
    include Mongoid::Document
    include Mongoid::Timestamps

    embeds_many :pictures

    attr_accessible :picture_image, :picture_image_cache, :picture_title
end

picture.rb

class Picture
    include Mongoid::Document
    mount_uploader :picture_image, Picture_imageUploader

    embedded_in :page 

    field :picture_image, :type => String
    field :picture_title, :type => String
end

form.html.erb

<%= simple_nested_form_for(@page) do |f| %>
    <%= f.fields_for :pictures do |f| %>
        <!-- This is a nested form -->

        <!-- Preview of previously uploaded picture -->
        <% @page.pictures.each do |picture| %>
            <%= image_tag picture.picture_image_url(:thumb).to_s %>
        <% end %>

        <!-- Upload button -->
        <%= f.input :picture_image, :as => :file, :label => 'Choose an Image:'%>

        <!-- Title for picture -->
        <%= f.input :picture_title, :label => 'Picture Title:'%>

         <%= f.link_to_remove "Delete this item" %>

    <% end %>
<% end %>

編集フォームで-[新しい画像をアップロード]ボタンのすぐ上に、以前にアップロードした画像のプレビューを表示したいと思います。上記のコードは、(明らかに)ループして各セクションのすべての画像を表示することを除いて機能しました。たとえば、「画像」のエントリが3つある場合、各「アップロード」ボタンの上に3つの画像すべてが表示されます。

その特定のエントリに関連する画像のみを表示したいのです。私はこのようなものがうまくいくと想像します<%= image_tag @page.picture_image_url(:thumb).to_s %>が、そうではありません。

私が見逃している単純でばかげた間違いは何ですか?

4

1 に答える 1

0

私はチェックしていませんがembeds_many :pictures、ループの関係は次のようにする必要があります。

<% @page.pictures.each do |picture| %>
  .
  .
  .
 <% end %>

あなたが何をしたいのかを理解していて、ループに画像を1つだけ表示したい場合は、次を試すことができます:

<% for picture in @page.pictures.limit(1).shuffle %>
 .
 .
 .
<% end %>

このコードで試してみてください!

于 2013-01-23T14:25:46.350 に答える