Rails模型外键验证

时间:2015-09-03 17:16:14

标签: ruby-on-rails validation ruby-on-rails-4

我需要在我的一个模型中验证外键引用的行的存在。情况是这样的:

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处理验证,所以我可以保持我的代码干。

修改

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

1 个答案:

答案 0 :(得分:1)

您似乎只需要在export PHANTOMJS_BIN=/usr/local/bin/phantomjs声明中添加foreign_key选项,以便指定您指定的自定义列名,即has_one而不是category_id 。有关详细信息,请参阅Options for has_one

project_category_id