gpt4 book ai didi

ruby-on-rails - Rails has_many, build, inverse_of

转载 作者:行者123 更新时间:2023-12-04 03:39:23 25 4
gpt4 key购买 nike

我有 2 个这样的模型:

class User < ActiveRecord::Base
has_many :user_services, :inverse_of => :user

validates_length_of :user_services, :maximum => 3
end

class UserService < ActiveRecord::Base
belongs_to :user, :inverse_of => :user_services

validates_associated :user
end

我想做类似的事情:
user_service = user.user_services.build(...)
if user_service.save
...

但它会引发“堆栈级别太深”错误。我假设是因为 validates_related 与 inverse_of 相结合。有谁知道为什么会这样?

直接在用户对象而不是 user_service 对象上调用 save 似乎有效,但我想知道是否有办法反向实现这些。

谢谢!

最佳答案

发生这种情况是因为您的验证具有循环依赖性。

validates_length_of :user_services
validates_associated :user

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated

更新

如果以这种方式重写代码,则可以删除循环依赖:
class User < ActiveRecord::Base
has_many :user_services, :inverse_of => :user
validates_length_of :user_services, :maximum => 3
end

class UserService < ActiveRecord::Base
belongs_to :user, :inverse_of => :user_services

def user_services_amount
return 0 if self.user.nil?
self.user.user_services.length
end

validates :user_services_amount, :inclusion => { :in => 0..3 }
end

关于ruby-on-rails - Rails has_many, build, inverse_of,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5711391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com