如果尚未设置属性或已删除属性,则寻找一种更干净的方法来设置默认值,并返回nil。
class Category < ActiveRecord::Base
has_and_belongs_to_many :restaurants
belongs_to :picture
def set_picture
if self.picture.nil?
Picture.default_pic
else
self.picture
end
end
end
class Picture < ActiveRecord::Base
belongs_to :review
def self.default_pic
Picture.new(url: "/assets/default.jpg")
end
end
# index.html.erb
<%= image_tag category.set_picture.url %>
类别中有很多餐厅,而餐厅有很多评论。评论有一对一的图片。应该允许类别从其关联的图片之一中进行选择,或者默认为素材资源文件夹中的图片。
#set_picture需要重构。希望对某种类型的回调:
class Category < ActiveRecord::Base
belongs_to :picture, defaults_to: Picture.default_pic
end
是否有上述回调?我可以创建一个吗?还是我的框架错了?
我认为您可以覆盖访问器并调用super。如果返回nil,则可以返回默认图片:
class Category < ActiveRecord::Base
belongs_to :picture
def picture
super || Picture.default_pic
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句