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!

4

1 回答 1

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.

于 2013-02-03T00:09:07.830 回答