3

So I was trying to just get an array of posts that do not include @post. To my surprise the code below resulted in @post being deleted from the database!

@post = Post.find(2)
@posts = Post.where(:text => "title")
@posts.delete(@post)

Why does an Array function delete @post from the database? Does Rails extend or overwrite this function? I thought only the .destroy function can delete objects from the database? I guess I am confused on what exactly the .where function returns and the consequences of using @ and not using @ for variables.

Thanks in advance!

1 Answers1

7

What is stored in @posts after you do Post.where(:text => 'title') is not an array. It's a type of ActiveRecord::Relation object.

When you call delete with @post as a parameter, you're telling Rails to delete that object from the database.

Zajn
  • 4,078
  • 24
  • 39
  • Here is the documentation of the method that is being called : http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete – Prakash Murthy Feb 03 '13 at 00:12
  • 2
    Glad I could help! If you want an array returned, you could simply do something like this: `Post.where(:text => 'title').to_a` – Zajn Feb 03 '13 at 01:05