【问题标题】:How to access attributes in a different model如何访问不同模型中的属性
【发布时间】:2011-11-22 18:57:11
【问题描述】:

我有两个模型

  • 缺席:金额,staff_id
  • 员工:身份证,请假余额

在缺勤模型中,我想编辑其 id 在 staff_id 中的员工,然后我想更改他们的 leave_balance 但我不知道如何根据当前模型中的 staff_id 访问员工模型中的该属性在缺席的情况下使用我的方法

【问题讨论】:

    标签: ruby-on-rails ruby oop


    【解决方案1】:

    首先查看广泛的Rails Guide to Active Record Associations 以了解该概念。

    那么你可以这样做:

    Staff.rb

    class Staff < ActiveRecord::Base
      has_one :absence # or has_many :absence
    end
    

    缺席.rb

    class Absence < ActiveRecord::Base
      belongs_to :staff
    end
    

    现在您可以通过Absence.first.staff.leave_balance -= 1 或在缺席模型self.staff.leave_balance = ... 中的实例方法中访问该属性

    【讨论】:

    • 我应该提到我已经建立了两者之间的关系,我无法弄清楚为什么数据库值没有更新,然后我突然想到我没有用值更新数据库:p
    • 很高兴您能够发现问题。
    【解决方案2】:

    你建立好关系了吗?

    在 Absence 类中,你应该有

    belongs_to :staff
    

    在 Staff 类中,你应该有

    has_many :absence
    

    完成后,您可以执行以下操作:

    a = Absence.last
    a.staff.leave_balance -= 1
    

    s = Staff.first
    s.leave_balance -= s.absences.count
    

    【讨论】:

      猜你喜欢
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多