gpt4 book ai didi

ruby-on-rails - Rails 中只有一个模型实例

转载 作者:行者123 更新时间:2023-12-04 03:37:17 24 4
gpt4 key购买 nike

我正在开发我的第一个 Rails 应用程序。它需要存储有关将出现在每个页面上的单个广告的一些信息。管理员只需要能够设置 URL、标题和图像。显然,我只需要这个广告对象的一个​​实例。

我创建了一个继承自 ActiveRecod::Base 的模型,但这似乎是错误的做法,因为它被配置为在数据库表中保存多个广告。

我这样做的最佳方法是什么?模型和 Controller 应该是什么样的?

提前致谢,
阿维

最佳答案

更好的方法是添加一个验证来检查一个记录条目是否已经存在。

在您的模型中:

validate :check_record, on: :create #please not that validate in this case is singular

def check_record
if Ad.all.count === 1
errors[:base] << "You can only have one active advertisement"
end
end

关于ruby-on-rails - Rails 中只有一个模型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1348811/

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