← Back to Upcase

What is the best way to set author field on STI model

(Shankar Dhanasekaran) #1

I have a basic model called Page and have many STI models based on Page such as





I have separate controller and view for each of these STI models because I needed to customized the view layer based on the model type and have different logic for controller and hence separate controllers. However, I need the author field of all models to be set to current user. How do I do this in a single place?

For example, if I use before_action on Page controller and set the author, it affects the @page instance variable whereas my DrawingsController is using @drawing so it wont save the author of my @drawing unless I repeat the same code in DrawingsController.

(Derek Prior) #2

You could use inheritance for all of the page controllers if there’s a good deal of shared functionality like this. If there isn’t, and it sounds like there is little in common, you could mix in a module that will be used when setting the parameters for your new objects. This is all untested and from memory and also assumes you’re using StrongParameters, but something like this…

module AuthoredByCurrentUser

  def create_params
     { user: current_user }
class ArticlesController
  include AuthoredByCurrentUser

  def create
    article = Article.new(create_params)

  def create_params

To be honest though, without seeing your actual code I’d probably nix the module and just merge the current user everywhere directly.