验证连接模型中的ID是一种好习惯吗?

时间:2017-02-13 22:55:51

标签: ruby-on-rails validation activerecord associations has-many-through

我在ArtistGroup型号之间设置了HMT关联:

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)

或在我的视图中创建表单(无ID输入)ActiveRecord足够智能地映射关联。有了这个,我应该在连接模型中验证这些ID吗?我注意到在处理多态关联时,这变得更加痛苦。

1 个答案:

答案 0 :(得分:0)

Rails 5自动要求belongs_to :artist引用现有artist,因此完全没有必要进行额外验证。您可以通过执行

使该要求成为可选项
belongs_to :artist, optional: true