:dependent => :破坏不起作用

时间:2014-03-24 16:19:30

标签: ruby-on-rails ruby associations

我读了许多关于关联的东西(belongs_to,has_many ......)但是我觉得我错过了某个地方,我找不到合适的答案。

这是我的帖子架构:

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

当我创建新帖子时,我发送" utilisateur_id"这样:

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

在rails控制台中,当我输入

user = Utilisateur.find(id)
user.posts

并且rails控制台找到与用户关联的帖子,是否意味着该关联有效?

在我的帖子模型中,我写了belongs_to :utilisateur, :dependent => :destroy,在我的utilisateur模型中,我写了has_many posts

当我销毁用户时,与之关联的帖子不会被销毁,我也不明白为什么。

谢谢!

1 个答案:

答案 0 :(得分:1)

has_many :posts, :dependent => :destroy