如何从属性中获取父对象类名

时间:2013-11-24 05:22:08

标签: ruby-on-rails object activerecord

是否可以返回给定属性的父对象?

实施例

  a = User.birthdate
  a.parent_object ... should return the user record that is the parent of the birthdate attribute

一个更好的例子?

辅助

 def item_grade(subject, obj)
     obj.scale.grades.find(subject.grade_id).name # would return something like "Pass", "Fail", "Good Job"
 end

在视图中

 item_grade(@course.subject, @course)

此方法需要将两个选项传递给帮助程序。看来我应该能够传递@ course.subject然后从那个

获取父对象

辅助

 def item_grade(subject)
     a = subject.parent_object.scale
     a.grades.find(subject.grade_id).name
 end

查看

 item_grade(@course.subject)

1 个答案:

答案 0 :(得分:2)

  

此方法需要将两个选项传递给帮助程序。

例如,您可以通过执行此操作来删除一些重复项。

 def item_grade(obj, property)
     obj.scale.grades.find(obj.send(property).grade_id).name
 end

 item_grade(@course, :subject)

现在您不必在通话中重复@course

必须传递两个参数比你想出的任何一种hackery都要小得多(感谢@muistooshort)。没有内置的方法来做到这一点。

相关问题