manish nautiyal
manish nautiyal

Reputation: 2584

Destroy is not working properly in rails 3

I'm using Rails-3 with psql

My problem is little bit funny. I don't know why its not working.

When I'm using this code everything is working perfectly

if @sd.supplier_document_users.first.status.eql?("Waiting")
   @sd.supplier_document_send_to_fi_user_lists.destroy_all
   @sd.supplier_document_users.first.destroy
   @fi_destroy_status = true
end

Here @sd.supplier_document_users return [] after this

When I add this if condition (if [email protected]_document_users.blank?) like this

if [email protected]_document_users.blank?              
    if @sd.supplier_document_users.first.status.eql?("Waiting")
       @sd.supplier_document_send_to_fi_user_lists.destroy_all
       @sd.supplier_document_users.first.destroy
       @fi_destroy_status = true
    end
end

Here @sd.supplier_document_users return value which I destroy above ( @sd.supplier_document_users.first.destroy)

I don't know what ghost come in my code.

Upvotes: 0

Views: 66

Answers (2)

spickermann
spickermann

Reputation: 106882

It's because the result of @sd.supplier_document_users may be cached by Rails.

In your second example @sd.supplier_document_users.blank? load all users in an array and caches the result. If you call @sd.supplier_document_users later again it is still the same array. If you want to make sure you reload the array, call: @sd.supplier_document_users(true).

It works in your first example, because there you do not load all users. Just the first (on database level, not on array level).

Upvotes: 1

Tumas
Tumas

Reputation: 1727

arguably it is much clearer with any?:

if @sd.supplier_document_users.any?              
    if @sd.supplier_document_users.first.status.eql?("Waiting")
       @sd.supplier_document_send_to_fi_user_lists.destroy_all
       @sd.supplier_document_users.first.destroy
       @fi_destroy_status = true
    end
end

Or you could write it like this:

if @sd.supplier_document_users.any? && @sd.supplier_document_users.first.status.eql?("Waiting")
   @sd.supplier_document_send_to_fi_user_lists.destroy_all
   @sd.supplier_document_users.first.destroy
   @fi_destroy_status = true
end

In any case how it is not working? Does the code inside an inner if is not being executed or are you expecting some sort of return value from if?

Upvotes: 1

Related Questions