2015-11-11 48 views
-2

我試圖在child_model中詢問parent的starting_on值。 我想比較,如果有相同的時期父模型的驗證值Child,Ruby on Rails

假設,我有這兩類

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 

我需要的是started_on值的父母

:parent.started_on回報我

undefined method 'started_on' for :project:Symbol 

而且我用這個驗證程序我的約會 Validators 感謝

+0

列出的':parent'是一個符號,你不能把它的方法 –

回答

1
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 
+0

日期與零比較失敗 – Arthur

+0

'>> self =>#' – Arthur

+0

'>> self.parent => nil' – Arthur

1

你想使用沒有標誌。

parent.started_on 

guides

+0

你的意思是這樣:'驗證:started_on,存在: true,date:{after:parent.started_on}'但是這樣不工作 – Arthur

+0

未定義的局部變量或方法'project_started_on'爲#' – Arthur

+1

如果您使用自定義事件得到你的幫助需要提及它。我想'驗證:starts_on,presence:true,date:{after:Proc.new {| x | '但我不知道這是否會奏效,因爲我不知道你在使用什麼。 –