如何运行上依赖于彼此的两个属性的回调函数? [英] How to run a callback function on two attributes that depend on each other?

查看:147
本文介绍了如何运行上依赖于彼此的两个属性的回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails应用程序,我有一个发票模型的属性日期 DUE_DATE

In my Rails app I have an Invoice model with the attributes date and due_date.

为了简单起见,我不希望用户手动输入 DUE_DATE 而是只需输入的天数应该是加入日期

For reasons of simplicity I don't want the user to manually enter the due_date but rather simply enter the number of days that should be added to the date.

这就是为什么我设置了一个虚拟属性 days_allowed

This is why I set up a virtual attribute days_allowed.

class Invoice < ActiveRecord::Base

  belongs_to :user

  before_save :save_date

  attr_accessor :days_allowed

  def days_allowed # attribute reader (I need that too!)
    (due_date - date).to_i
  end

  def save_date
    self.due_date = date + days_allowed.days
  end

end

然而,当用户拿起的形式的日期,并进入若干天,例如 10 ,我得到错误的结果,因为 save_date 回调是指 days_allowed 方法,而不是同一个名字的属性

However, when a user picks a date in the form and enters a number of days, e.g. 10, I get wrong results because the save_date callback refers to the days_allowed method rather than the attribute of the same name.

问题的关键似乎是,我使用的两个是互相依赖的(日期 days_allowed )。

The key problem seems to be that I am using the callback on two different attributes that depend on each other (date and days_allowed).

谁能告诉我如何解决这个难题?

Can anybody tell me how to solve this puzzle?

感谢您的帮助。

推荐答案

这个怎么样的方法(没有 before_save 是必要的):

How about this approach (no before_save is necessary):

class Invoice < ActiveRecord::Base

  belongs_to :user

  def days_allowed
    (due_date - date).to_i
  end

  def days_allowed=(days)
    self.due_date = date + days
  end
end

修改不应该与质量分配工作时,既日期 days_allowed 是present除非日期总是先行。

EDIT Not supposed to work with mass assignment when both date and days_allowed are present unless date always goes first.

这篇关于如何运行上依赖于彼此的两个属性的回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆