Is subclassing a User model really bad to do in Rails?

后端 未结 3 1218
我寻月下人不归
我寻月下人不归 2021-01-04 23:30

I am getting lots of push back from Rails because I have subclassed User into many different subclasses. In my application, not all users are equal. There\'s actually a lot

3条回答
  •  无人及你
    2021-01-04 23:52

    It's basically about "say what you mean",

    the framework has no way of knowing when you say redirect_to @user if you meant the generic user form or the specialized employee user form.

    This leads to a lot of redirect_to @user.becomes(User) which you're free to DRY up

    def to_base_class
      becomes User
    end
    alias_method :to_b, :to_base_class
    

    and write redirect_to @user.to_b when your intention is to redirect to User and not Employee resource

    Basically, elegant syntax like redirect_to @user represents very deep coupling between model and view/controller and as you make the model and view/controller logics more complex cracks due to this coupling will begin to show and some additional effort in domain separation will need to be made or a bit more code will need to be written.

    Rails isn't punishing you for using OOP, you're experiencing increased complexity of model <-> view <-> controller relationship:

    once upon a time you model was your view and vice versa, now you have two model classes mapped to two view classes and if you want to use one view for the other model you will have to say it

提交回复
热议问题