【问题标题】:find_or_create_by trying to create duplicate records with hmt associationfind_or_create_by 尝试使用 hmt 关联创建重复记录
【发布时间】:2017-02-09 09:24:49
【问题描述】:

我很好奇是否还有其他方法可以实现以下目标。

设置:

class Cabin < ApplicationRecord
  has_many :feature_groupings
  has_many :features, through: :feature_groupings
end

class Feature < ApplicationRecord
  has_many :feature_groupings, dependent: :destroy
  has_many :cabins, through: :feature_groupings

  validates_uniqueness_of :name
end

class FeatureGrouping < ApplicationRecord
  belongs_to :feature
  belongs_to :cabin
end

c1 = Cabin.create(name: "Standard")
c2 = Cabin.create(name: "Luxury")
c1.features.create(name: "Wifi")
f = c2.features.find_or_create_by(name: "Wifi")

这会导致

2.4.0 :006 > f.errors.full_messages
 => ["Name has already been taken"]

有没有一种更简洁的方式将功能(id:1,名称:“Wifi”)与 c2(id:2,名称:“Luxury”)关联起来,而不是简单地:

c2.features << Feature.find_or_create_by(name: "Wifi")

我曾期望使用 HMT 关联 find_or_create 该功能会产生某种 Rails 魔术。

Rails 版本:5.0.1

Ruby 版本:2.4.0

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    我认为问题在于,这样做:

    f = c2.features.find_or_create_by(name: "Wifi")
    

    您正在尝试在与 c2 关联的特征中查找或创建特征。这就是它失败的原因,所以不,我认为没有(很多)更好的方法可以做到这一点,因为您想添加现有功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多