find_or_create_by试图创建与hmt关联的重复记录

问题描述:

我很好奇是否有其他方式实现以下功能。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

我相信问题是,在这样做的:

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

你正在努力寻找或创造与c2相关的功能中的功能。这就是为什么它失败了,所以不,我不认为有一个(很多)更好的方法来做到这一点,因为你想添加一个现有的功能。