Ruby on rails Rails—为什么我的自定义验证只针对一个构建命令触发

Ruby on rails Rails—为什么我的自定义验证只针对一个构建命令触发,ruby-on-rails,validation,Ruby On Rails,Validation,我有一个句子和修正模型,分别有一个has_-one和一个属于关系 因为某种原因,当我这样做的时候 def create @sentence = Sentence.find(params[:sentence_id]) @correction = @sentence.build_correction(params[:correction]) 我编写的用于更正的自定义验证将在build_更正点调用。下面是验证 class Correction < Act

我有一个句子和修正模型,分别有一个has_-one和一个属于关系

因为某种原因,当我这样做的时候

 def create

        @sentence   = Sentence.find(params[:sentence_id])
        @correction = @sentence.build_correction(params[:correction])
我编写的用于更正的自定义验证将在build_更正点调用。下面是验证

class Correction < ActiveRecord::Base
   attr_accessible :text, :sentence_id, :user_id
   belongs_to :sentence
   belongs_to :user

   validate :correction_is_different_than_sentence

   def correction_is_different_than_sentence
     errors.add(:text, "can't be the same as the original sentence.") if (text == self.sentence.text)
   end
class Correction
问题是由于验证的某些原因,更正对象没有设置句子id(尽管我使用了build_更正方法),因此它会抱怨 在上面的验证中,if子句中的“执行nil.text时有nil对象…”


所以我的问题是,为什么要对构建命令进行验证,我认为它只会在创建或更新时触发。为什么这句话还没定下来呢?

一如既往,这不是rails的错,而是我自己的错——它很琐碎,很难解释,对任何人都没有用,所以我不会解释

一些错误让我很头疼。不知道为什么,但将自定义验证器调用移动到其他验证器调用的末尾为我解决了这个问题

之前

  validates :name, :short_description, presence: true
  validate :uniq_name
  validates :price, :numericality => {:greater_than_or_equal_to => 0}
  validates_attachment_content_type :image, :content_type => /image/
之后

  validates :name, :short_description, presence: true
  validates :price, :numericality => {:greater_than_or_equal_to => 0}
  validates_attachment_content_type :image, :content_type => /image/
  validate :uniq_name
这是我的自定义验证器

private

def uniq_name
  return if clone?
  user_product = self.user.products.unlocked.where(:name => self.name).first
  errors[:name] << "has already been taken" if user_product && !user_product.id.eql?(self.id)
end
private
def uniq_名称
如果是克隆,返回?
user\u product=self.user.products.unlocked.where(:name=>self.name)。第一个

错误[:name]我想如果你注释掉“attr\u accessible:text,:句子\u id,:user\u id”就行了,谢谢你的回复。不幸的是,它没有改变任何事情