Rails优先于类方法与数据库字段

我有一个Picture类,我想覆盖返回“description”数据库列值取决于一些逻辑。

这在Rails中有效吗? 在返回数据库列值之前,我是否可以始终依赖类来调用类方法?

# database columns for Picture class # description => String # parent_id => Integer class Picture < ActiveRecord::Base def description if parent_id.nil? self.description else description = Picture.find(parent_id).description end end end 

无法找出在Rails源代码中找到答案的位置,因此任何帮助都将不胜感激。

谢谢!

编辑

我正在尝试返回图片的描述,具体取决于它是否为子图片或父图片(它们可以嵌套)。 这个例子有点人为……我可以通过使用一个与数据库列没有相同名称的方法来轻松避免这种情况……例如

 def my_description if parent_id.nil? # return db data since no parent self.description else # return parent's description if one exists description = Picture.find(parent_id).description end end 

我想我想在这里不必要地复杂化

目前还不完全清楚你要做什么,但你可以使用super从方法中获取描述值:

 def description if parent_id.nil? super else self.description = Picture.find(parent_id).description end end 

请注意,我更改了最后一行以使用self.description =因为我假设您要设置描述值。 如果不是这样,那么您不需要将其分配给任何变量。

您应该在描述方法中使用read_attribute(:description)(可以覆盖)。

此外,您可以在else部分中执行parent.description而不是Picture.find rigmarole。 使用我确定你拥有的父协会。

 def description # if parent_id is there and the parent object can be found and that parent has a description if (parent_id? && parent && parent.description?) # show parental description parent.description else # read my own database attribute read_attribute(:description) end end 

不确定分配给上面的描述是否会做任何事情,因为它最终会成为局部变量。 而做自我描述=在读者只是有点讨厌恕我直言。