简体   繁体   中英

:dependent => :destroy does not work

I read lot of stuff about association (belongs_to, has_many ...) but I think I missed a point somewhere, and I can't find the right answer.

Here's my schema for posts:

create_table "posts", force: true do |t|
t.string   "titre"
t.text     "description"
t.string   "hastag"
t.string   "postimg"
t.integer  "utilisateur_id"
t.datetime "created_at"
t.datetime "updated_at"
end

add_index "posts", ["utilisateur_id"], name: "index_posts_on_utilisateur_id", using: :btree

When I create a new post, I send the "utilisateur_id" this way:

@post = Post.new(post_params)
current_user = session[:utilisateur_id]
@post.utilisateur_id = current_user

In the rails console, when I type

user = Utilisateur.find(id)
user.posts

and the rails console finds the posts associated with the user, does it mean that the association worked?

In my post model, I wrote belongs_to :utilisateur, :dependent => :destroy and in my utilisateur model, I wrote has_many posts .

When I destroy the user, the posts associated with it are not destroyed, and I don't understand why.

Thanks!

has_many :posts, :dependent => :destroy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM