【问题标题】:has_many :through and join table in Railshas_many :在 Rails 中通过和连接表
【发布时间】:2019-09-12 22:24:45
【问题描述】:

我想为我的应用程序正确实施数据库和相关模型。

我有两个模型:userlocation。由于我需要保留有关这两个实体之间关联的历史数据,因此我希望它们通过表连接起来。

因此,除了location_iduser_id 的外键之外,我还创建了一个名为user_locations 的连接表,我还有两个需要的字段。

到目前为止一切顺利。

一个新的需求出现了,我需要我的location 是多态的。 我不知道如何正确设置我的模型来存储以便能够拥有该连接表和多态关联。

这是我到目前为止的想法:

user.rb

class User < ApplicationRecord

  has_many :locations, through: :user_locations, as: :locationable, source_type: 'User'
  has_many :user_locations
end

location.rb

class Location < ApplicationRecord
  belongs_to :locationable, polymorphic: true
  has_many :users
end

user_location.rb

class UserLocation < ApplicationRecord
  belongs_to :user
  belongs_to :location

  validates_presence_of :user
  validates_presence_of :location

end

【问题讨论】:

  • 似乎唯一需要该位置的模型是用户。对吗?
  • 现在是的。但该位置将在未来属于其他型号。在每种情况下,例如user_location 我需要一个连接表来存储一些额外的信息

标签: ruby-on-rails ruby activerecord ruby-on-rails-5 rails-activerecord


【解决方案1】:

我发现了一篇很好的教程/文章I think can help you here.

这需要你做类似的事情:

class User < ApplicationRecord
  has_many :locations
  has_many :model_ones, through: :locations, source: :locationable, source_type: 'ModelOne'
  has_many :model_twos, through: :locations, source: :locationable, source_type: 'ModelTwo'

还有:

class Location < ApplicationRecord
  belongs_to :locationable, polymorphic: true
  belongs_to :user
end

ModelOneModelTwo 里面显然填的是你需要的模型。

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    相关资源
    最近更新 更多