GEkk
GEkk

Reputation: 1366

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 :)

Upvotes: 2

Views: 183

Answers (3)

Richard Peck
Richard Peck

Reputation: 76774

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

Upvotes: 2

Arpit Vaishnav
Arpit Vaishnav

Reputation: 4780

Also, In the model you can create a call back too. Every time you create or update any row, this field will be updated before committing any stmt

before_commit :set_approved_terms_time

def set_approved_terms_time
   approved_terms_time = DateTime.now
end

Upvotes: 2

cnnr
cnnr

Reputation: 1307

Also you can do something like this:

def update_user
  resource_params.merge(user_id: current_user.id)
end

But I think that the AR-callbacks usage is the cleanest and best solution.

Upvotes: 0

Related Questions