When I delete a post model record, I want to delete a comment model record associated with it, but I get the following error.
Currently, if there is no comment, it can be deleted normally.
If anyone understands, please take care of me.
error messages:
Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails (`anipho_development`.`comments`, CONSTRINT`fk_rails_2fd19c0db7`FOREIGN KEY(`post_id`) REFERENCES````d``))
The current code looks like this
Migration Files
class CreateComments <ActiveRecord::Migration [6.0]
def change
create_table:comments do | t |
t.references:user,foreign_key:true
t.references:post,foreign_key:true
t.string:content, null:false
t.timestamps
end
end
end
comment.rb
class Comment <ApplicationRecord
belongs_to —user
belongs_to —post
values:content, presence:true
end
post.rb
class Post <ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash —category
belongs_to —user
has_one_attached —image
has_many:comments,dependent::destroy
with_options presence —true do
validates:image
validates:title
values:category_id,numberality:{other_than:1,message:"Choose from something other than --"}
end
end
user.rb
class User<ApplicationRecord
# Include default device modules.Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
device:database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many —posts
has_many —Comments
PASSWORD_REGEX=/\A(?=.*?a-z])(?=.*?\d)[a-z\d]+\z/i.freeze
values:nickname, presence:true
values:password,format:{with:PASSWORD_REGEX}
end
The cord looks like it's going to work properly.
How do you delete the post model?
There are several ways to delete a record, but Rails generally uses one of the four ActiveRecord methods.
delete, delete_all, destroy, destroy_all.
There are four things that may be confusing, but in order to delete them so that they don't get the error,
@post=Post.find(params[:id]
@post.destory
You need to erase it like this.
There are four deep-fried methods, delete and destory.
The difference is
Defined in Post Model
has_many:comments, dependent::destroy
This. This dependency definition is equivalent to a callback and will not be executed if deleted using the delete method.
Therefore, the following SQL will be issued as soon as the method is executed.
DELETE FROM posts where id=xxxx
As the migration file in CreateComments defines the FK,
t.references:post,foreign_key:true
The records in the comments table are always configured to have the id of the records in the parent posts table.
If you delete the posts record with the comments left, the comments will float in orphaned state, so there is an FK error to prevent them.
To avoid this error, you must first erase the comments records, but to do so, you must use the destroy method as well as the definition of dependent::destroy
.
© 2024 OneMinuteCode. All rights reserved.