Reputation: 207
I have a program submitting an HTTP request to my Rails application every five minutes. These records have an index on ID & created_at to display in reverse order. Due to the frequency of these status updates, I only want to store the most recent ten of them. While researching how to do this, I figured an offset would be perfect to retrieve and then delete a dataset. Though in my rails console tests, I haven't been able to convince ActiveRecord that it wants to work that way (it deletes all of the records instead of just the ones not included in offset).
Is there a more efficient way to do what I'm trying to do in my controller? And is there a way to delete records with an offset using ActiveRecords? If not, what would be the ideal way to go about doing it?
def create
env = Env.find_by_name(params[:updateresult][:env_name])
@updateresult = env.updateresults.build(updateresult_params)
respond_to do |format|
if @updateresult.save
format.json { render json: @updatresults, status: :created}
#env.updateresults.where(:id => env.updateresults.offset(10).pluck(:id)).delete_all
else
format.json { render json: @updatresults.errors, status: :unprocessable_entity }
end
end
end
Edit: Altered David's answer to come up with the commented out answer in the above code
Upvotes: 0
Views: 752
Reputation: 52376
I don't think that you can use an offset in a delete, so you'd probably have to:
delete from my_table
where id in ( select id
from my_table
order by created_as desc
offset 10);
So:
MyTable.where(:id => MyTable.order("created_at desc").offset(10).pluck(:id)).delete_all
Of course you could just delete records more than 50 minutes old?
Upvotes: 5