如何关联来自不同 类 Rails 的属性

How to associate attributes from different classes Rails

我很难将 Rails 上的事物联系起来。在这种情况下,我有一个本地模型和一个用于标识用户令牌(来自另一个 APi)的模型。一个地方有一个与之相关的评分(从 0 到 5 的分数),每个用户都有很多评分,但每个地方只有一个。为了做到这一点,我创建了一个具有评级属性的新模型,我想将评级 ID 关联到一个地点 ID。

# Description of User Identifier Class
class UserIdentifier < ApplicationRecord
  has_many :favorite_locals, dependent: :destroy
  has_many :user_rate, dependent: :destroy
  validates :identifier, presence: true
  validates_numericality_of :identifier
  validates_uniqueness_of :identifier

  def self.find_favorites(params)
    UserIdentifier.find(params).favorite_locals
  end
end

# Model of Users Rates 
class UserRate < ApplicationRecord
    belongs_to :user_identifier
    validates :rating, numericality: true
    validates_numericality_of :rating, less_than_or_equal_to: 5
    validates_numericality_of :rating, greater_than_or_equal_to: 0
    validates :user_identifier, presence: true
end

首先,您在 has_many :user_rate, dependent: :destroy 中有错别字。该协会应命名为 user_rates,因此 UserIdentifier 模型的正确代码为:

class UserIdentifier < ApplicationRecord
  has_many :favorite_locals, dependent: :destroy
  has_many :user_rates, dependent: :destroy
  # ...
end

其次,不清楚 "place" 实体在您的项目中是如何命名的。如果是 FavoriteLocal 那么这就是您需要的代码:

class UserRate < ApplicationRecord
    belongs_to :user_identifier
    belongs_to :favorite_local
    # ...
end

如果这是另一个模型,只需在 belongs_to :user_identifier 下方定义属于关联。我希望你明白了。