[英]Rails model foreign key validation
我需要在我的一个模型中验证外键引用的行的存在。 情况是这样的:
Project.rb
class Project < ActiveRecord::Base
has_one :project_category
# -----------------------------------------------------------------
# this does not work because the attribute is actually called
# 'category_id' instead of the rails expected 'project_category_id'
# -----------------------------------------------------------------
validates :project_category, presence: true
end
项目移转
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
# ----------------------------------------------
# this is why the column is called 'category_id'
# ----------------------------------------------
t.references :category, references: :project_categories, null: false
# all of my other fields here, unimportant
end
add_foreign_key :projects, :project_categories, column: :category_id
end
end
我知道我可以编写一个自定义的验证方法来检查:category_id
存在于project_categories
表中,但我更愿意让Rails处理验证(如果可以的话),因此可以使代码保持DRY。
编辑
ProjectCategory.rb
class ProjectCategory < ActiveRecord::Base
belongs_to :project
validates :name, presence: true, uniqueness: { case_sensitive: false }
end
ProjectCategory迁移
class CreateProjectCategories < ActiveRecord::Migration
def change
create_table :project_categories do |t|
t.string :name, null: false
end
end
end
看来,您只需要在has_one
声明中添加foreign_key
选项,即可指定您指定的自定义列名,即category_id
而不是project_category_id
。 有关详细信息,请参见has_one的选项 。
# app/modeles/project.rb
class Project < ActiveRecord::Base
has_one :project_category, foreign_key: 'category_id'
# -----------------------------------------------------------------
# this does not work because the attribute is actually called
# 'category_id' instead of the rails expected 'project_category_id'
# -----------------------------------------------------------------
validates :project_category, presence: true
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.