简体   繁体   English

模型 Child、Ruby on Rails 中父级的验证值

[英]Validation value of parent in model Child, Ruby on Rails

I'm trying to ask the started_on value of parent in child_model.我试图在 child_model 中询问 parent 的 started_on 值。 I want to compare, if it has the same period我想比较一下,如果它有相同的时期

assumed, I have these two classes假设,我有这两个类

class Parent < ActiveRecord::Base
  has_many :children
end

And this class, Child_Class:而这个类,Child_Class:

class Child < ActiveRecord::Base
  belongs_to :parent
  validates :name, presence: true, :length => { :minimum => 2, :maximum => 50 }
  validates :finished_on, presence: true, date: {not_equal: :started_on}
  validates :started_on, presence: true, date: {after: :parent.started_on}
end

What I need is the started_on value of parent我需要的是 parent 的 started_on 值

:parent.started_on returns me :parent.started_on返回我

undefined method 'started_on' for :project:Symbol

And I'm using this validators for my date Validators Thanks我正在使用这个验证器作为我的日期验证器谢谢

You want to use it without a symbol.您想在没有符号的情况下使用它。

ie IE

parent.started_on

As outlined in the guides指南中所述

class Child < ActiveRecord::Base
  belongs_to :parent
  validates :name, presence: true, :length => { :minimum => 2, :maximum => 50 }
  validates :finished_on, presence: true, date: {not_equal: :started_on}
  validate :validate_started_on

  private

  def validate_started_on
    return if parent.nil?
    return if started_on > parent.started_on
    errors.add :started_on, :should_be_after_the_parent_started_on 
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM