Rails 3/4 Rails 脚手架 .update 方法导致 Heroku 上的索引顺序发生变化

Rails 3/4 Rails Scaffold .update method causes index order to change on Heroku

我构建了一个网络应用程序来测试购买咖啡。

我使用 rails 生成脚手架来制作我的物品供应商:

rails generate scaffold vendor expresso_count:integer cuppucino_count:integer 

它还有一些上面没有包括的其他变量,但它们都是整数类型

当用户购买咖啡时,vendor 中的变量例如:cuppucino_count 会更新。它在使用 .update

的供应商控制器中使用此自定义方法
     def purchase_pass
@vendor = Vendor.find(params[:id])

# checks vendor pass
if @vendor.vendor_pass.to_s == vendor_params[:vendor_pass]
  flash[:success] = "Thank you for your purchase of 1x #{ params[:type] }."
  #updates coffee type
  if params[:type] == 'Espresso'
    coffee_count = @vendor.expresso_count
    coffee_count = coffee_count +1
    @vendor.update(expresso_count: coffee_count)
  end

  redirect_to purchase_thanks_path
else
  flash[:error] = "Pass incorrect. Please ensure you enter the correct pass."
  render :purchase
end

结束

由此 link 执行的操作。

  <p><%= link_to vendor_purchase_path(id: @vendor.id, type: 'Americano') do %> <span style="font-size: 300%;" class="fa fa-coffee"></span>Americano <% end %></p>

在 Heroku 上,供应商的 index.html 视图,每当使用 edit.html 视图或 .update 方法更新供应商时,供应商显示的顺序就会改变。

即:如果有

Vendor 1, Vendor 2, Vendor 3

变为

Vendor 2, Vendor 3, Vendor 1 

如果更新的是供应商 1

但是我的本地安装顺序没有改变。

知道是什么原因造成的吗?

这是我的 git 回购的 link:https://bitbucket.org/umlungu/mybeans

与问题相关的是 @vendors 变量是如何在 index 方法中设置的;这将决定索引页中显示的内容。

如果您保留了脚手架中的代码,那么它很可能如下所示:

def index
  @vendors = Vendor.all
end

这将在 table 上运行 select * from vendors 查询。

请注意查询没有任何排序子句。来自 postgres documentation for select

If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce. (See ORDER BY Clause below.)

这就解释了为什么在本地和 heroku 上显示的顺序不同。

要使结果按特定顺序显示,请按如下方式指定顺序子句:

def index
  @vendors = Vendor.order(:id)
end