【问题标题】:Rails association for two foreign keys for the same table in one table一个表中同一个表的两个外键的Rails关联
【发布时间】:2009-12-11 13:31:13
【问题描述】:

我是 RoR 的新手,还在玩联想。我需要在另一个模型中有两个对特定模型的引用。脚手架代码不起作用,我收到“未初始化的常量”错误。

生成命令:

script/generate scaffold BaseModel name:string
script/generate scaffold NewModel name:string base1:references base2:references
db:migrate

生成的模型:

class NewModel < ActiveRecord::Base
     belongs_to :base1
     belongs_to :base2
end

class BaseModel < ActiveRecord::Base
     has_many :new_models # I added this line
end

当我尝试在/new_models/new 创建一个 new_model 时,我尝试了 BaseModel 的 ID 和名称,但它不起作用。我得到的错误是:

uninitialized constant NewModel::Base1

我猜它映射了名称,所以在我的 create 方法中,我尝试显式设置 BaseModel 实例:

@new_model = NewModel.new(params[:new_model])
@base1 = BaseModel.find(1) # this exists
@base2 = BaseModel.find(2) # this exists
@new_model.base1 = @base1  # This throws the same error as above

我有什么遗漏的吗?

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    Rails 的大部分魔法 来自约定优于配置。通过根据指南命名,Rails 可以猜出大多数配置选项。 ActiveRecord::Associations 也不例外。

    任何 ActiveRecord 关联的第一个参数是将在模型中使用的名称。这通常是另一个模型的名称,这是约定。默认情况下,类名是驼峰形式的关联名的单数。关联中的默认外键是带有“_id”后缀的关联名称。如果您的关联名称与这些模式中的类名称或外键不匹配,您需要将它们作为选项提供。

    这会做你想做的事:

    class NewModel
      belongs_to :base1, :class_name => "BaseModel"
      belongs_to :base2, :class_name => "BaseModel"
    end
    

    就我个人而言,我会给关联命名比 base1 和 base2 更具描述性。像这样的:

    评分表:id、rater_id、rated_id、rating

    class Rating
      belongs_to :rater, :class_name => "User"
      belongs_to :rated_user, :class_name => "User", :foreign_key => "rated_id"
    end
    

    本可以使用不同的示例,但选择此示例是为了突出何时需要外键选项。

    【讨论】:

      【解决方案2】:

      传递给belongs_to 方法的符号需要是另一个模型的单数名称。因此,对于您的示例,它将是:

      class NewModel < ActiveRecord::Base 
        belongs_to :base_model 
      end 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-12
        • 2023-01-21
        • 2015-12-30
        • 2019-12-23
        • 2019-02-18
        • 1970-01-01
        相关资源
        最近更新 更多