如何从嵌套模型引用高级模型?

发布于 2024-11-03 12:11:03 字数 898 浏览 2 评论 0原文

我正在尝试根据付款模型中的项目状态进行条件验证。例如,状态可以是“对话”或“活动”。考虑到下面的结构,最好的方法是什么?

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 :value2, :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

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 :value2, :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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑白记忆 2024-11-10 12:11:03
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文