在销毁回调之前

问题描述:

我是一位Rails API的新手Ruby程序员。我有一个位置模型和一个用户模型,一个位置有很多用户。它们的关系如下:在销毁回调之前

class Location << ActiveRecord::Base 
    has_many: :users 
end 

class User << ActiveRecord::Base 
    belongs_to :location 
end 

我想提出一个约束的选址模型,这样,如果有一个或多个相关用户一个位置模型对象不会被破坏。

考虑孟买的情况,这是一个位置,它有一个或多个用户。因此,我无法摧毁那个位置;只有在特定位置没有用户的情况下,我才能销毁。

如何以受保护的方式处理销毁记录,如此?

+0

你可以把支票在销毁行动,如果:

class Location << ActiveRecord::Base has_many: :users before_destroy :check_for_users def check_for_users return if users.any? errors[:base] << "some error message" false end end 

话,甚至可以在你的控制器访问错误信息location.users.present?然后限制删除。 –

您可以更新您的选址模型,看起来像这样:

class Location << ActiveRecord::Base 
    before_destroy :confirm_safe_to_destroy 

    has_many: :users 

private 

    def confirm_safe_to_destroy 
    return false if users.any? 
    end 
end 

这将使用before_destroy处理程序来检查是否安全地销毁Location mod el对象。如果有任何用户与位置关联,则confirm_safe_to_destroy方法返回false以停止销毁进程。

+0

谢谢。有效。 :) – Abhishek

只需添加这样的事情你的模型:

# in app/models/location.rb 
before_destroy :ensure_no_users 

private 
def ensure_no_users 
    return false if users.any? 
end 

在您的选址模型添加以下内容:

before_destroy :check_for_users #This will be run before destroy is called. 



def check_for_users 
    return false if self.users.present? 
end 
+0

非常感谢,它工作! :) – Abhishek

你也可以添加一个错误消息实例:

if @location.destroy? 
    # success flow - location was deleted 
else 
    @location.errors.full_messages #=> "some error message" 
end 
+0

谢谢。有效。 :) – Abhishek