I am in the process of writing a Ruby on Rails web application for my university's department.
For some of our resources in the web application, e.g. Project
, are complex with their view layer logic:
- a
Project
can be created byadmin
orfaculty
users. - after submission,
faculty
cannot update some attributes of theirProject
. student
users can view the project that they participate in, but can't update any attributes at all (view only).- new
Project
should hide some fields that are visible in the show action, because those fields are updated by anadmin
after submission of the form - many more rules...
Currently I have a single form for each type of action: new, show, and edit. The problem is that the business rules are lodged in the views in a very complex manner. I originally did this to prevent having a separate form for each user (that the controller would render based on the user's role
), which had a lot of code duplication. The business logic will only get more complicated over time, making the single-form approach more complex to develop and maintain. But at the same time, separating out the forms into role
-specific views causes an increase in code duplication.
So, on to the question. Would creating separate forms for each user role
make sense, given that it would essentially be 50% code duplication? Is there a better solution that that?
The actual attributes that are allowed to be updated are actually controlled via Rails strong parameters and the Pundit gem which allows to scope resources based on rules (such as User.role
). What I'm talking about is solely the presentation layer.
As an aside, I have already tried working with partials for shared form fields; however, I eventually need to move x
or y
field out of the partial and back into the complicated single form because some business rule changes to restrict access to certain fields to certain roles.
I have also looked at this MVC question which is pretty similar, but it's ASP.NET which might have a difference in how these rules could be separated out of the view; I've never worked with ASP.NET so I don't know. This general MVC question also doesn't answer my question; my business rules are already present in my models and through the Pundit gem; however, how to best present this data is not discussed.