How to refer to high-level model from nested one?
I'm trying to make conditional validation based on Project status in Payment model. For example status can be "Talks" or "Active". What's the best way to do it considering the structure below?
class Project < ActiveRecord::Base
has_many :costs, :dependent => :destroy
has_many :payments, :through => :costs, :dependent => :destroy
accepts_nested_attributes_for :costs, :allow_destroy => true
end
class Cost < ActiveRecord::Base
has_many :payments, :dependent => :destroy
accepts_nested_attributes_for :payments, :allow_destroy => true
belongs_to :project
end
class Payment < ActiveRecord::Base
belongs_to :cost
validates_presence_of :value1, :if => :new?
validates_presence_of :value1, :if => :talks?
validates_presence_of :va开发者_StackOverflow中文版lue2, :if => :active?
def new?
# if controller action is new
end
def talks?
# if project status is "Talks" (edit action)
end
def active?
# if project status is "Active" (edit action)
end
end
class Payment < ActiveRecord::Base
belongs_to :cost
has_one :project, :through => :cost
validates_presence_of :value1, :if => :new?
validates_presence_of :value1, :if => :talks?
validates_presence_of :value2, :if => :active?
def new?
self.new_record?
end
def talks?
project.status == "talks"
end
def active?
project.status == "active"
end
end
精彩评论