3

考虑以下简化模型

class Article < ActiveRecord::Base
  has_many :taggings
  has_many :tags, through: :taggings
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :articles, through: :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :article
  validates :tag_id, :article_id, presence: true
end

除了尝试为它编写测试外,我几乎都遵循了标记 railscast 。

在 Railscast 中没有使用但我自己添加的 Tagging 模型中的验证让我有些头疼。

如果我创建一篇新文章,我可以传递一个标签列表:

a = Article.new(title: "title", tag_list: "tag 1, tag 2")
a.valid? 
#=> false 
a.errors
# => 
  @base=#<Article id: nil, title: "title">, 
  @messages={:taggings=>["is invalid", "is invalid"]}> 

所以看起来我的标记类的验证导致文章创建失败,因为article_id它还不可用。

人们通常在这里做什么?是否习惯将此类验证添加到连接表或可以跳过?

4

1 回答 1

1

I would suggest that Tagging validates the presence of :tag and :article, rather than the IDs. This has two benefits:

  1. If the article is a new record, the Tagging will still be valid.

  2. If the article_id is invalid (e.g. -1), the Tagging will be invalid.

I disagree with the previous commenters' suggestion to remove the validation altogether, validations help avoid creating bad records. E.g a Tagging with an article but not a tag.

于 2012-12-15T18:25:56.727 回答