简体   繁体   English

Ruby on Rails使用设置生成ActiveRecord模型

[英]Ruby on Rails generate ActiveRecord model with settings

I need to create model by generating in terminal with command 我需要通过在终端中使用命令生成模型
rails generate model ...

How can i set validation of uniqueness on one of column, and name of primary_key field using that command? 如何使用该命令在列之一上设置唯一性验证,以及primary_key字段的名称? I found how could it be done by: 我发现如何做到这一点:
rails g model model_name field_name1:type:uniq field_name2:type:primary_key...

It sets for the table in database primary_key and uniqueness on certain fields with the migration. 它为数据库中的表primary_key设置表,并随迁移设置某些字段的唯一性。 However i want to define settings for the ActiveRecord model which will be stored in "ModelName.rb" file in the "models" folder of my project. 但是,我想为ActiveRecord模型定义设置,该设置将存储在我项目的“模型”文件夹中的“ ModelName.rb”文件中。

For now i call the ModelName.validates_uniqueness_of(:field_name) method every time when I operate with records of model to prevent adding record with duplicate values on :field_name1 现在,每次我处理模型记录时,我都会调用ModelName.validates_uniqueness_of(:field_name)方法,以防止在:field_name1上添加重复值的记录

You can use the validate helper uniqueness: true which validates the uniqueness of the attribute's value right before the object gets saved. 您可以使用validate helper uniqueness: true来在保存对象之前立即验证属性值的唯一性。

class ModelName < ActiveRecord::Base
  validates :field_name1 uniqueness: true
end

And, as @Abhi pointed out for you, take a look at the Active Record Validations Documentation. 并且,正如@Abhi为您指出的,请查看Active Record验证文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM