0
我有我的Artist
和Group
模型之間的HMT關聯安裝:驗證連接模型中的ID是否是一種好的做法?
class Artist < ApplicationRecord
has_many :artist_groups, dependent: :destroy
has_many :artist_groups, through: :artist_groups
end
class ArtistGroup < ApplicationRecord
has_many :memberships, class_name: "ArtistGroupMembership", dependent: :destroy
belongs_to :artist
belongs_to :group
has_and_belongs_to_many :roles
accepts_nested_attributes_for :memberships, reject_if: :all_blank, allow_destroy: true
validates_presence_of :artist_id, :group_id
end
class Group < ApplicationRecord
has_many :artist_groups, dependent: :destroy
has_many :members, through: :artist_groups, source: :artist
end
正如你會發現在我的ArtistGroup
加入模型,可以驗證,以確保一個藝術家和團體都存在。
當關聯保存,無論我做這樣的事情:
artist.groups.push(Group.first)
或在我看來,創建表單(SANS ID輸入)ActiveRecord的是足夠聰明的映射關係。有了這個在我應該我甚至在我的連接模型驗證這些ID?我注意到這在處理多態關聯時變得更加痛苦。