【问题标题】::dependent => :destroy does not work:dependent => :destroy 不起作用
【发布时间】:2014-03-24 16:19:29
【问题描述】:

我阅读了很多关于关联的资料(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,在我的实用模型中,我写了has_many posts

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

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby associations


    【解决方案1】:
    has_many :posts, :dependent => :destroy
    

    【讨论】:

    • 正如 backparkerhh 所说,您希望在您的 User 模型上进行依赖销毁。如果您删除他们拥有的帖子,您当前拥有的方式将删除用户。这将使其余的帖子成为孤立的。
    • 哦,好吧,我知道我错过了一个重点。非常感谢。我在 post 模型中编写了依赖销毁,因为在 Mysql on delete => cascade 中是子级,而不是父级。它的工作就像一个魅力。再次感谢!
    • 完成了,stackoverflow 要求我等待 500 万才能接受。
    猜你喜欢
    • 1970-01-01
    • 2016-10-23
    • 2011-02-17
    • 2010-10-21
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多