gpt4 book ai didi

ruby-on-rails - 模型验证是否应反射(reflect)数据库列约束

转载 作者:行者123 更新时间:2023-12-04 10:59:46 24 4
gpt4 key购买 nike

我有下表:

class CreatePosts < ActiveRecord::Migration[6.0]
def change
create_table :posts do |t|
t.belongs_to :site, null: false
t.bigint :post_id, null: false
t.string :title, null: false
t.string :url, null: false
t.text :body, null: false

t.timestamps
end
end
end

你可以看到,没有属性可以有值 null .我应该在 Post 中反射(reflect)这些限制吗?模型?这是一个好习惯吗?

现在,如果我尝试保存没有所有属性的帖子,ActiveRecord 将引发 MySQL 错误,我希望避免这种情况并提供更简洁的错误。

最佳答案

在这个问题上,让我尊重巨型机器人撞向其他巨型机器人:
https://thoughtbot.com/blog/validation-database-constraint-or-both

在这篇文章中,德里克·普赖尔建议几乎没有必要同时做这两件事:

It is not necessary to back each validation with a schema constraint, nor is it necessary for schema constraints to be reflected as model validations. There are a couple of questions worth asking as you decide which is appropriate for your use case.

  1. Are you trying to prevent bad data from being written to the database? If so, you must have a schema constraint. Unfortunately, Omakase Rails doesn’t natively support the creation and schema dumping of all common constraints supported by Postgres, so you must also weigh this in your decision making.

  2. Are you preventing errors that your application user can fix for themselves? If so, you should use a model validation.



我建议阅读整篇文章(我已经并且发现自己每隔几个月就会回到它)。

关于ruby-on-rails - 模型验证是否应反射(reflect)数据库列约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895981/

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