Reputation: 826
I need to validate the existence of a row referenced by a foreign key in one of my models. The situation is like this:
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
Project Migration
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
I know that I can write a custom validation method to check if the :category_id
exists in the project_categories
table but I would prefer to let rails handle the validation if there is a way, so I can keep my code DRY.
EDIT
ProjectCategory.rb
class ProjectCategory < ActiveRecord::Base
belongs_to :project
validates :name, presence: true, uniqueness: { case_sensitive: false }
end
ProjectCategory Migration
class CreateProjectCategories < ActiveRecord::Migration
def change
create_table :project_categories do |t|
t.string :name, null: false
end
end
end
Upvotes: 0
Views: 440
Reputation: 38645
It appears you only need to add the foreign_key
option to your has_one
declaration in order to specify the custom column name you've specified i.e. category_id
instead of project_category_id
. See Options for has_one for details.
# 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
Upvotes: 1