2015-09-03 123 views
0

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

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_idproject_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

看样子你只需要添加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 
+0

阅读完文档并给出一个尝试后,它看起来像':foreign_key'选项定义了传递给'has_one'关联的表中外键的名称。在这种情况下,我需要在'project_categories'表中使用'project_id'字段来使用这个选项,这不是当前我的模式设置的方式。 – steve

+0

您可以更新您的问题,以便在设置时包含两个迁移和模型关系。 – vee

+0

是的,请参阅编辑。 – steve