Rails 3:循环显示的记录多于应有的记录

时间:2013-02-13 20:10:22

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

不完全确定要将此问题称为什么。还是铁杆新手。

情况:拍卖包含许多批次 我正在以 / auctions / 3 / lots / 等网址展示拍卖品。

查看:

<ul>
<% @lots.each do |lot| %>
  <li><%= lot.auction_id %>: <%= lot.id %></li>
<% end %>
</ul>

输出:

<ul>
  <li>3: 1</li>
  <li>3: </li>
</ul>

我的数据库中只有一个 lot 。不确定额外循环实例的来源。
这种情况发生在任何批次列表中,无论我正在查看哪个拍卖

另外,
<%= @lots.length %>显示2
<%= @lots.size %>显示2
<%= @lots.count %>显示1

我的lots_controller看起来像这样:

def index
  @auction = Auction.find(params[:auction_id])
  @lots = @auction.lots
end

def create
  @auction = Auction.find(params[:auction_id])
  @lot = @auction.lots.build(params[:lot])

  if @lot.save
    redirect_to auction_lots_path, :notice => 'Lot was successfully created.'
  else
    render :action => "index"
  end
end

我的模特:

class Auction < ActiveRecord::Base
  ...
  has_many :lots
end

class Lot < ActiveRecord::Base
  belongs_to :auction
  ...
end

...只是attr_accesssiblevalidates行。

请求我点击页面时的日志,就在这里。

Started GET "/auctions/8/lots" for 127.0.0.1 at 2013-02-13 16:35:51 -0500
Processing by LotsController#index as HTML
  Parameters: {"auction_id"=>"8"}
  Auction Load (0.1ms)  SELECT "auctions".* FROM "auctions" WHERE "auctions"."id" = ? LIMIT 1  [["id", "8"]]
  Lot Load (0.2ms)  SELECT "lots".* FROM "lots" WHERE "lots"."auction_id" = 8
[#<Lot id: 18, description: "1923 Morgan", lot_number: 1, auction_id: 8, created_at: "2013-02-13 17:20:04", updated_at: "2013-02-13 17:20:04">]
  Rendered layouts/_messages.html.erb (0.1ms)
  Lot Exists (0.2ms)  SELECT 1 AS one FROM "lots" WHERE "lots"."auction_id" = 8 LIMIT 1
  Rendered lots/index.html.erb within layouts/application (9.4ms)
Completed 200 OK in 21ms (Views: 17.8ms | ActiveRecord: 0.5ms)

更新
有人提到看起来我在某处使用@auction.lots.build 是的,我是。我在同一页面(索引)上有一个表单,我可以在其中添加批量。

<%= form_for(@auction.lots.build, :url => auction_lots_path(@auction)) do |f| %>
  ...
<% end %>

更改@auction.lots.build删除了额外的行,但现在我无法成功创建批次。我不知道该怎么做。我可能要在lots_controller的index方法中设置一些东西,但我不知道是什么。

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

如果批次无法保存,则会在您的create方法中发生这种情况。因为您使用了@auction.lots.build,所以会在拍卖中附加大量记录。如果它没有正确保存,它仍然没有保存。这就解释了为什么“神秘”的人没有身份,也是为什么:

<%= @lots.size %>显示2 <%= @lots.count %>显示1

@lots.count是一个数据库查询,但@lots.size只是内存中数组的大小。

我可能会在创建动作中做更多这样的事情:

def create
  @auction = Auction.find(params[:auction_id])
  @lot = @auction.lots.create!(params[:lot])
  redirect_to auction_lots_path, :notice => 'Lot was successfully created.'
rescue ActiveRecord::RecordInvalid
  render :action => "index"
end

...但当然其他人会更喜欢使用if / else而不是拯救异常。还有其他方法。你可以@auction.reload.lots来剔除未保存的那个,但这有点奇怪。在这种情况下,正常的rails事件是重新呈现表单并显示验证错误,并要求用户修复它们并尝试重新创建。

答案 1 :(得分:-1)

这应该有所帮助:

def create
  params[:lot].merge!({:auction_id =>  params[:auction_id]})
  @lot = Lot.new(params[:lot])

  if @lot.save
    redirect_to auction_lots_path, :notice => 'Lot was successfully created.'
  else
    render :action => "index"
  end
end