【问题标题】:Rails - a model belongs_to other models single referenceRails - 一个模型属于_其他模型的单一参考
【发布时间】:2015-02-03 16:38:05
【问题描述】:

简单的关联问题。 我有一个包含以下字段的 Location 模型: - 姓名 - 地址 - 纬度 - 长

这个模型应该有很多“locationables”。

好的。我还有以下型号:

Lodging
has_one location (location id)

Transportation
has_one start_location, class_name: location
has_one end_location, class_name: location

那么,在这种情况下,我的位置模型中应该有一个“belongs_to”吗?或者我不需要任何东西,只需将“belongs_to”放在其他模型中?这似乎是错误的,对吧?看起来很简单,但我的脑子却没有解决它。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    要创建正确的交叉引用,您需要在类中有::belongs_to::has_and_belongs_to_many 关联来启动直接引用。第一个在类中创建class_id 字段(和属性读取器),第二个附加交叉引用连接表命名为“class_klasses”。如果您没有任何一个,您可以通过绑定类来正确设置引用,因为::has_one::has_many 只使用反向引用,而不是直接引用。因此,您将需要以下内容:

    class Locationable < ...
       belongs_to :location
    end
    
    class Lodging < ...
       belongs_to :location
    end
    
    class Transportation < ...
       belongs_to start_location, class_name: :Location
       belongs_to end_location, class_name: :Location
    end
    

    或者当然要保持数据库更干净,您可以使用through 键(例如)Lodging 类,但前提是您已经有一个关联:

    class Locationable < ...
       belongs_to :location
    end
    
    class Lodging < ...
       belongs_to :locationable
       has_one :location, through: :locationable
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多