Rails 相当于 Django 的“选择”
我知道 Rails 中没有真正的等效项,但我的问题主要是关于最佳实践...
在 Django 中,如果您想将模型字段限制为一组有限的选择,您可以执行以下操作(在您的模型中):
COLOR_CHOICES = (('B', 'Blue'), ('R', 'Red'))
item_color = models.CharField(choices=COLOR_CHOICES)
根据我对 Rails 的(基本)理解,我可以实现类似的目标,例如,通过在处理添加/编辑该模型的表单中使用选择标签...
但是我的问题是,在哪里声明“选择”哈希(我再次猜测哈希就是我需要的?)。基本上,我只是希望它能够以任何可能需要呈现这些选择的形式以及在模型级别进行验证时轻松地重复使用。
任何帮助/提示将不胜感激!
I know there is no real equivalent in Rails but my question is mostly about best practice...
In Django, if you want to limit a model field to a limited set of choices, you would do something like this (in your model):
COLOR_CHOICES = (('B', 'Blue'), ('R', 'Red'))
item_color = models.CharField(choices=COLOR_CHOICES)
From my (basic) understanding of Rails, I can achieve something similar, for example, by using a select tag in the forms dealing with adding/editing that model...
My question however is, where would it be appropriate to declare the "choices" hash (again I'm guessing here that a hash is what I need?). Basically I just want it to be easily re-usable in any forms where I might need to present those choices, and when it comes to validating at the model level.
Any help/tips would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在验证方面,可能 validates_inclusion_of 就是您所需要的:
至于生成帮助程序,您可以尝试以下操作:
然后在某些帮助程序中:
On the validation side of things, probably validates_inclusion_of is what you need:
As for generating the helper, you can try something like:
And then in some helper:
您可以简单地使用枚举
更多信息: https://api .rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Enum.html
You can simply use enum
More information here : https://api.rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Enum.html
2年后,有一个更好的选择:values_for
2 years later, there's a better option: values_for