Ruby on rails 如果属性为nil,则ActiveRecord默认值

Ruby on rails 如果属性为nil,则ActiveRecord默认值,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,正在寻找一种更简洁的方法,在属性尚未设置或已被删除并返回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

正在寻找一种更简洁的方法,在属性尚未设置或已被删除并返回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_图片进行重构。希望是某种类型的回调:

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
类别