How can I delete some data from DB if there is no primary key?
Using RoR 3.0.7. (ruby 1.9.2)
I have a table books (model Book) with following fields:
book_id - int (not a primary key)
cover_pic - varchar
year - year
I need to delete * rows from DB with books_id = 1 for example.
Have tried:
1) Book.where(:book_id=>1).destroy (nothing)
2) Book.dest开发者_运维知识库roy( Book.where(:book_id=>1) ) (nothing)
3) Book.where(:book_id=>1).each do |obj|
obj.destroy
end
NOTHING .. =(
what am I doing wrong?
thx.
UPD
worked fine delete_all
interesting info: undefined method `eq' for nil:NilClass with rails 3 and ruby enterprise on ubuntu hardy
You can use either of these two:
This will fire all destroy callbacks
Book.destroy_all( :book_id => 1 )
This won't
Book.delete_all( :book_id => 1 )
Assuming you have some unique index on the table, this works great:
book = Book.first
Book.delete_all(book.attributes)
If you don't have a unique index on the table, the above is dangerous - you could nuke more rows than anticipated. If that is the case, either add a unique index on an existing column (or columns) or else add a PK to the table.
精彩评论