1
我很好奇是否有其他方式實現以下功能。find_or_create_by試圖創建與hmt關聯的重複記錄
設置:
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"]
是否存在關聯特徵的更清潔的方式與C2(ID(ID: 「WiFi」 的:1,名):2名:「豪華」)比簡單:
c2.features << Feature.find_or_create_by(name: "Wifi")
我原本以爲會有某種軌道魔術使用HMT協會到find_or_create
該功能。
Rails的版本:5.0.1
的Ruby版本:2.4.0