sigh STI rears it’s ugly head. That’s not to say I don’t like this solution… I do. It’s nice and simple. I’m just always a bit wary when it’s introduced.
Anyway, there’s a bit of refactoring I would do. I would change:
# in ApplicationController#current_user
AnonymousUser.find_or_initialize_by_token(anonymous_user_token).tap do |user|
user.save(validate: false) if user.new_record?
end
to something like this:
AnonymousUser.safely_find(anonymous_user_token)
and push the find_or_initialize_by_token and save(validate: false) into the model.
Moving the user lookup/create into the model is definitely a nice refactor. You’re right about STI—it usually gets ugly when you use it without necessity. I mostly went with it for clarity of demonstration. I personally prefer using roles to denote user traits.
I love this concept! I agree that making people sign up to get basic content is a huge barrier, and this solution of using an AnonymousUser (I’m guessing single-table inheritance here?) is so elegant in that it keeps all of database relationships intact if the user decides to sign up.
sigh STI rears it’s ugly head. That’s not to say I don’t like this solution… I do. It’s nice and simple. I’m just always a bit wary when it’s introduced.
Anyway, there’s a bit of refactoring I would do. I would change:
to something like this:
and push the
find_or_initialize_by_tokenandsave(validate: false)into the model.Moving the user lookup/create into the model is definitely a nice refactor. You’re right about STI—it usually gets ugly when you use it without necessity. I mostly went with it for clarity of demonstration. I personally prefer using roles to denote user traits.
Of Rails' open bugs, about half are ActiveRecord, and STI (from my rough estimate) are about a third of those.
I love this concept! I agree that making people sign up to get basic content is a huge barrier, and this solution of using an
AnonymousUser(I’m guessing single-table inheritance here?) is so elegant in that it keeps all of database relationships intact if the user decides to sign up.