سؤال

I have a Post model which belongs to a User.
I display the Username like this: @post.user.name If a user cancels their account, it will no longer work because the user is nil.
Is there a way to have a fallback user (e.g. "Deleted user")?

I though about disabling users instead of deleting them, but in some cases i might want to delete them.

هل كانت مفيدة؟

المحلول

There is a concept called Null Pattern, you could implement something like this

class NullAuthor
  def name
    "Deleted user"
  end
end

and you would use it like this inside your ActiveRecord model

class Post < ActiveRecord::Base
  belongs_to :user

  def author
    @author ||= if user.present?
                  user
                else
                  NullAuthor.new
                end
  end
end

In this way, you never have to check if the post user is nil or not :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top