Ruby on Rails finding last saved record
In a scenario I am finding the last saved record using the code
last = Category.find(:last)
This is to assign the id of category as the parent id to the sub-categories.
And so, I am assigning the it in this manner.
@subcategory.parent_id = last.id
This works fine, but when multiple users are tryin开发者_运维百科g to create Categories, then there is a wrong assignment of parent_id to the subcategory. (Sometimes it takes the id of a different category if that was created last.)
Is there any other way to find the last record?
Instead of doing a separate database query, you should be making changes at the same time.
If it is not possible to find the category you want by more specific means, i.e last = Category.find_by_name('category I actually want')
, then update both your Category
and the relevant Subcategories
in the same place (your controller or model, however you've got it set up).
Try this example...it might help you:
<% Specimen.find(:all, :order => 'distribution_sheet_id DESC', :limit => 10).each do |df| %>
<%= df.id %>
<% end %>
精彩评论