簡體   English   中英

模型 Child、Ruby on Rails 中父級的驗證值

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

我試圖在 child_model 中詢問 parent 的 started_on 值。 我想比較一下,如果它有相同的時期

假設,我有這兩個類

class Parent < ActiveRecord::Base
  has_many :children
end

而這個類,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

我需要的是 parent 的 started_on 值

:parent.started_on返回我

undefined method 'started_on' for :project:Symbol

我正在使用這個驗證器作為我的日期驗證器謝謝

您想在沒有符號的情況下使用它。

IE

parent.started_on

指南中所述

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