【问题标题】:How to associate attributes from different classes Rails如何关联来自不同类 Rails 的属性
【发布时间】:2018-10-13 18:40:53
【问题描述】:

我在 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

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    首先,您在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
    

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

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

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

    【讨论】:

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