我想在销毁记录时阻止rails尝试从连接表中删除。
所以,如果我有
class User
has_and_belongs_to_many :projects
end
class Project
has_and_belongs_to_many :users
end
当我致电user.destroy
时,rails会尝试从联接表projects_users
中删除记录。我可以阻止它这样做吗? delete_sql
似乎没有。
我想这样做的原因是我希望能够使用数据库视图将复杂的关系表现为rails关联以用于报告目的。
答案 0 :(得分:0)
我认为创建另一个模型UserProject
更容易,并执行以下操作:
class User
has_many :user_projects
has_many :projects, through: :user_projects
end
class Project
has_many :user_projects
has_many :users, through: :user_projects
end
class UserProject
has_many :users
has_many :projects
end
这样,当您致电user.destroy
时,它会在:dependent
中查找提供给has_many
的{{1}}选项,以确定如何处理相关对象。如果您将其设置为User
,则会删除:nullify
对象,但关联的user
和user_project
s 将拥有其project
个外键设置为user_id
,因此不会被销毁。
Here是使用NULL
和why you should prefer not to use has_and_belongs_to_many的文档。