【问题标题】:Rails model foreign key validationRails 模型外键验证
【发布时间】: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


    【解决方案1】:

    看来您只需将foreign_key 选项添加到您的has_one 声明中,即可指定您指定的自定义列名称,即category_id 而不是project_category_id。详情请见Options for 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
    

    【讨论】:

    • 在阅读文档并尝试一下之后,:foreign_key 选项定义了表中传递给 has_one 关联的外键的名称。在这种情况下,我需要 project_categories 表中的 project_id 字段来使用此选项,这不是我当前设置架构的方式。
    • 您能否更新您的问题,以在设置时包含两个迁移和模型关系。
    • 如果您在project_categories 中有belongs_to :project,那么您应该将project_id 外键添加到您的project_categories 模型中。
    • project_categories 只是一个查找表。我在这里错过了什么吗?我不想在 project_categories 表中为 project 表中的每一行添加一个新行。
    • 如果我理解正确,那么您在projects 表中有外键,它告诉project_categoryproject 属于哪个?它是否正确?您能否改为开始聊天,我认为解决问题会更快。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多