Car*_*rpk 1 ruby activerecord ruby-on-rails
如果尚未设置属性或已删除属性,则寻找更简洁的方法来设置默认值,并返回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 %>
Run Code Online (Sandbox Code Playgroud)
类别有很多餐馆,餐馆有很多评论.评论有一对一的图片.应该允许类别从其相关图片中选择一个,或者默认为assets文件夹中的图像.
#set_picture需要重构.希望某种类型的回调:
class Category < ActiveRecord::Base
belongs_to :picture, defaults_to: Picture.default_pic
end
Run Code Online (Sandbox Code Playgroud)
是否有回复执行上述操作?我可以创建一个吗?或者我的框架错了?
我想你可以覆盖访问者并调用super.如果返回nil,则可以返回默认图片:
class Category < ActiveRecord::Base
belongs_to :picture
def picture
super || Picture.default_pic
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
973 次 |
最近记录: |