【发布时间】:2015-09-03 17:16:14
【问题描述】:
我需要验证我的一个模型中是否存在由外键引用的行。情况是这样的:
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
项目类别迁移
class CreateProjectCategories < ActiveRecord::Migration
def change
create_table :project_categories do |t|
t.string :name, null: false
end
end
end
【问题讨论】:
标签: ruby-on-rails validation ruby-on-rails-4