Search code examples
ruby-on-railsassociationsrails-activerecordstrong-parameters

Rails, add strong param with controller to every param require


I have a simple rails nested attributes params, I would like to know if there is a possibility to add my own value before update/create. like in the line :

:approved_terms_time => DateTime.now

def post_params
  params.require(:post).permit(:title, :content, user_attributes: [:id, :approved_terms, :approved_terms_time => DateTime.now])
end

I certainly can do so in the Create \ update:

@user.approved_terms_time = DateTime.now

But I would like to know whether there is a more elegant way :)


Solution

  • Model

    To add to @Arpit Vaishnav's answer, this type of process should be extracted to the model. The data you're appending is non-input dependent, and can therefore be added with impunity.

    There are a number of ActiveRecord callbacks which provide you with an off-hand way to manipulate data you wish to add to your model.

    I would personally use before_create:

    #app/models/post.rb
    class Post < ActieRecord::Base
       before_create :set_terms_time
    
       private
    
       def set_terms_time
           approved_terms_time = DateTime.now
       end
    end