rails for loop产生额外的

时间:2014-06-23 20:43:47

标签: ruby-on-rails ruby-on-rails-3

我通过图片的这个简单部分继续得到额外的空循环: 基本上我在专辑中有3个图像,我不断得到4个循环(1个空的额外)。任何简单的解决方案?

<% @album.pictures.each do |picture|%>
  <div class="col-md-4">
   <div class="panel panel-default">
    <div class="panel-thumbnail">
         <%= image_tag picture.file_url((:album),:class=> "img-responsive") if picture.file? %>
      <div class="panel-body">
        <p class="lead">name</p>
        <p>description</p>
        <p>
            <%= button_to "remove", album_picture_path(:picture_id => picture.id, :album_id => @album.id), :confirm => 'Are you sure?', :method => :delete, :class => :destroy %>
        </p>
      </div>
    </div>
  </div>
  </div><!--/col-->
   <% end %>

Picture Controller.rb

def index
    @album = Album.find(params[:album_id])
    @albumpicture = @album.pictures
    @pictures = @albumable.pictures.all
    render :json => @pictures.collect { |p| p.to_jq_upload }.to_json
  end

  def show
    @picture = Picture.find(params[:id])
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @pictures }
    end
  end

  def new
    @album = Album.find(params[:gallery_id])
    #@picture = @album.pictures.build
    #@picture = Picture.new(:album_id => params[:album_id])
  end

Album_controller.rb

def index
    @albums = @albumable.albums
       respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @albums }
    end
  end

  def show

    @album = @albumable.albums.find(params[:id])
    # @picture = @album.pictures.build
    # @pictures = Picture.find(:all, :conditions => ['album_id = ?', @album.id])
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @album }
    end

  end

  def new
    @album = @albumable.albums.new
    @album.token = @album.generate_token
    # @picture = @album.pictures.build
    # @pictures = []

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @album }
    end
  end

_fileupload.html.erb

<%= form_for @album.pictures.new, :html => { :multipart => true, :id => "fileupload"  } do |f| %>

1 个答案:

答案 0 :(得分:0)

我将详细解释上面的评论,假设你有一个控制器动作,你初始化你想要在表单中使用的新图片对象:

def show
  @album = Album.find(params[:id])
  @new_picture = @album.pictures.new
end

此时我们假设这张专辑中没有图片,如果你做了<%= @album.pictures.count %>,那么你可以在show.html.erb中找到0作为结果,但它会是1因为即使图片未保存,您也会在相册中初始化一个图片对象。

在这种情况下我做了什么,我从控制器中删除了新对象,并将其直接放在表单中:

<%= form_for @album.pictures.new, do |f| %>

<%= form_for Picture.new, do |f| %>
  <%= f.hidden_field :album_id %>
<% end %>

并确保在保存图片时保存album_id,如果不在导轨3中,则可能需要在attr_accessible Picture.rb中设置{{1}}