在销毁回调之前
before destroy call back
我是一名新手 Ruby 程序员,正在 Rails API 工作。我有一个 Location 模型和一个 User 模型,一个位置有很多用户。它们是这样相关的:
class Location << ActiveRecord::Base
has_many: :users
end
class User << ActiveRecord::Base
belongs_to :location
end
我想对 Location 模型施加约束,以便 Location 模型对象在具有一个或多个关联用户时不会被销毁。
考虑孟买的情况,它是一个位置并且有一个或多个用户。因此,我不能破坏那个位置;只有在特定位置没有用户时我才能销毁。
如何以受保护的方式处理销毁记录,例如这样?
只需将类似这样的内容添加到您的模型中:
# 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
您可以将位置模型更新为如下所示:
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 模型对象是否安全。如果有任何用户与该位置关联,confirm_safe_to_destroy
方法 returns false 停止销毁过程。
您还可以向实例添加错误消息:
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
然后您甚至可以在您的控制器中访问错误消息:
if @location.destroy?
# success flow - location was deleted
else
@location.errors.full_messages #=> "some error message"
end
我是一名新手 Ruby 程序员,正在 Rails API 工作。我有一个 Location 模型和一个 User 模型,一个位置有很多用户。它们是这样相关的:
class Location << ActiveRecord::Base
has_many: :users
end
class User << ActiveRecord::Base
belongs_to :location
end
我想对 Location 模型施加约束,以便 Location 模型对象在具有一个或多个关联用户时不会被销毁。
考虑孟买的情况,它是一个位置并且有一个或多个用户。因此,我不能破坏那个位置;只有在特定位置没有用户时我才能销毁。
如何以受保护的方式处理销毁记录,例如这样?
只需将类似这样的内容添加到您的模型中:
# 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
您可以将位置模型更新为如下所示:
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 模型对象是否安全。如果有任何用户与该位置关联,confirm_safe_to_destroy
方法 returns false 停止销毁过程。
您还可以向实例添加错误消息:
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
然后您甚至可以在您的控制器中访问错误消息:
if @location.destroy?
# success flow - location was deleted
else
@location.errors.full_messages #=> "some error message"
end