Rails 3.1 - 每个循环的额外结果?

时间:2012-07-02 11:19:41

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

这很简单,但我会有点疯狂,可能会遗漏一些盯着我的东西。有人可以帮忙吗?

基本上,我有一个简单的每个循环,它返回一个额外的流氓行。即使数据库中没有任何内容,我也会返回一行!

我的节目视图包括循环:

  <p id="notice"><%= notice %></p>

<p>
  <b>Header:</b>
  <%= @mailer.header %>
</p>

<p>
  <b>Subtext:</b>
  <%= @mailer.subtext %>
</p>

<div id="" class="" padding-left: 30px;>    
<h3>Mailer Products </h3>

<ol id="mailer-Product-list">
<% @mailer.mailer_products.sort_by { |mailer_products| mailer_products.position }.each  do |mailer_product| %>
    <%= content_tag_for :li, mailer_product do %>
    <%= mailer_product.product.cat_no %>
<% end %>
<% end %>
</ol>   

    <%#= link_to 'Done', @product, :class => "standard-button" %>
</div>



<%= form_for([@mailer,@mailer.mailer_products.build]) do |f| %>

    <div class="field">
    <%= f.label :product_id %><br />
    <%= f.text_field :product_id %>
    </div>

    <div class="field">
    <%= f.hidden_field :mailer_id, :value => @mailer.id %>
    </div>

    <div class="actions">
    <%= f.submit "Add Product" %>
    </div>
<% end %>


<%= link_to 'Edit', edit_mailer_path(@mailer) %> |
<%= link_to 'Back', mailers_path %>

控制器代码为:

class MailersController < ApplicationController

  def show
    @mailer = Mailer.find(params[:id])
     respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @mailer }
     end
   end

class MailerProductsController < ApplicationController

  def index
    @mailer_products = MailerProduct.find(:all)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render :json => @mailer_products }
    end
  end
end

end

2 个答案:

答案 0 :(得分:2)

您对form_for的来电看起来像这样

form_for([@mailer,@mailer.mailer_products.build]) do |f|

您会收到一个额外的空白项目,因为.build上调用mailer_products的内容是:它会向数组附加一个新实例

当表单在循环之后这没关系,但是当事情是循环的另一种方式将在修改后的数组上

答案 1 :(得分:0)

我通常的错误是在循环中添加<%=而不是<% ...

<%= @foo.each do |itme| %>
# do stuff
<% end %>

应该是

<% @foo.each do |itme| %>
# do stuff
<% end %>

仔细检查你的标签......