gpt4 book ai didi

ruby-on-rails - rails : How to limit number of items in has_many association (from Parent)

转载 作者:行者123 更新时间:2023-12-03 13:25:54 26 4
gpt4 key购买 nike

我想限制关联中的项目数量。我想确保用户拥有的东西不超过 X。这个问题was asked before并且解决方案在 child 身上具有逻辑:

提供的解决方案(针对类似问题):

class User < ActiveRecord::Base
has_many :things, :dependent => :destroy
end

class Thing <ActiveRecord::Base
belongs_to :user
validate :thing_count_within_limit, :on => :create

def thing_count_within_limit
if self.user.things(:reload).count >= 5
errors.add(:base, "Exceeded thing limit")
end
end
end

硬编码的“5”是个问题。我的限制根据 parent 而变化。事物的集合知道它相对于用户的限制。在我们的例子中,经理可以为每个用户调整(事物)的限制,因此用户必须限制其事物的集合。我们可以让 thing_count_within_limit 向其用户请求限制:
if self.user.things(:reload).count >= self.user.thing_limit

但是,这是很多 用户 来自事物的内省(introspection)。多次调用用户,尤其是 (:reload)对我来说是危险信号。

对更合适解决方案的思考:

我以为 has_many :things, :before_add => :limit_things会起作用,但我们必须对 stop the chain 提出异常.这迫使我更新 things_controller 来处理异常,而不是 if valid? 的 rails 约定。或 if save .
class User
has_many :things, :before_add => limit_things

private
def limit_things
if things.size >= thing_limit
fail "Limited to #{thing_limit} things")
end
end
end

这是Rails。如果我必须如此努力,我可能做错了什么。

为此,我必须更新父模型、子 Controller ,并且我不能遵循约定?我错过了什么吗?我误用了 has_many, :before_add ?我使用 :before_add 查找了一个示例,但找不到任何示例。

我考虑过将验证移至用户,但这只发生在用户保存/更新时。我没有看到使用它来停止添加事物的方法。

我更喜欢 Rails 3 的解决方案(如果这对这个问题很重要)。

最佳答案

因此,如果您想为每个用户设置不同的限制,您可以将 things_limit:integer 添加到 User 中并执行

class User
has_many :things
validates_each :things do |user, attr, value|
user.errors.add attr, "too much things for user" if user.things.size > user.things_limit
end
end

class Thing
belongs_to :user
validates_associated :user, :message => "You have already too much things."
end

使用此代码,您无法将 user.things_limit 更新为低于他已经获得的所有东西的数字,当然它限制用户通过他的 user.things_limit 创建东西。

应用示例 Rails 4:

https://github.com/senayar/user_things_limit

关于ruby-on-rails - rails : How to limit number of items in has_many association (from Parent),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8153051/

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