简体   繁体   中英

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

I built a webapp to test buying coffee.

I used rails generate scaffold to make my item Vendor:

rails generate scaffold vendor expresso_count:integer cuppucino_count:integer 

It has a few other variables not included above, but they all of type integer

When a user purchases a coffee, a variable in vendor eg: cuppucino_count is updated. It uses this custom method in the Vendor controller which uses .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

end

Which is actioned by this 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>

On Heroku, the index.html view for vendors, the order that the vendors get displayed changes whenever a vendor gets updated using either the edit.html view or the .update method.

ie: if there was

Vendor 1, Vendor 2, Vendor 3

It changes to

Vendor 2, Vendor 3, Vendor 1 

if Vendor 1 was the one updated

However the order doesn't change on my local installation.

Any ideas what is causing this?

Here is a link to my git repo: https://bitbucket.org/umlungu/mybeans

What is relevant to the question is how the @vendors variable is being set in the index method; that is the one which will determine what is being displayed in the index page.

If you have left the code from the scaffold as it is, then it will most likely look as follows:

def index
  @vendors = Vendor.all
end

This runs a select * from vendors query on the table.

Note that the query does not have any ordering clause. From the 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.)

So that explains why the order displayed is different locally and on heroku.

For making the results show up in a specific order, specify the order clause as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM