DataMapper delete works but only after restarting my app
I have two models, User and Snippet:
class User
include DataMapper::Resource
property :id,Serial
...
has n,:snippets
end
class Snippet
include DataMapper::Resource
property :id,Serial
...
belongs_to :user
end
When I'm displaying the snippets, I'm using this:
snippets = user.snippets
And when I'm deleting them I'm using this:
snippet = Snippet.first(:user_id => user.id,:id => snip_id)
if snippet
destruction_res = snippet.destroy
...
end
The thing is, destruction_res always returns true. I tried saving the user after I deleted the snippet. It returned true as well. The thing is, when I access the view that uses the code:
snip开发者_如何转开发pets = user.snippets
it returns the complete list, including the snippet which should have been destroyed. If I restart the application however, I see the correct list. What am I doing wrong? Should I somehow force a commit to the database?
It's possible that you're loading the snippets collection before destroying a snippet then you access that collection again and it still includes the deleted snippet. If that's the case, you can reject a destroyed snippet like that:
user.snippets.reject!(&:destroyed?)
BTW - you can destroy a snippet like this:
user.snippets.get(snip_id).destroy
A bit nicer :)
精彩评论