Rails Strong Parameters Shortcut for Scoping current_user to Record
Primespot Engineering - June 06, 2020
This one kind of blew my mind. To be honest, I’m not quite sure why I never thought of it. I got this tip from https://gorails.com while watching the episode titled Realtime Group Chat with Rails [Revised] - Part 2.
In this episode, Chris Oliver (founder of gorails.com) showed his method for scoping the current_user to a record in a controller.
First of all, this tip is pure Ruby. Before I get into it, let me show you what I’ve been doing so far in my Rails controllers.
def create
@record = Record.new record_params
@record.user = current_user
...
end
This works great. And in some situations, it might be better than the shortcut I’m going to show you. It’s definitely a bit more flexible than the shortcut.
This shortcut takes advantage of the Ruby Hash.merge method. This method merges a hash into another hash. It’s sort of like JavaScript’s Object.assign() function.
private
def record_params
params.require(:data).permit(:value, :another).merge(user: current_user)
end
By chaining the merge method onto the params.require.permit chain, we’re able to add the current_user to the return value of record_params. This will assign the correct user value to the newly created record in one line instead of two.
This:
def create
@record = Record.new record_params
@record.user = current_user
...
end
Becomes:
def create
@record = Record.new record_params
...
end
I won’t use this approach in all situations. Sometimes I will prefer the flexibility of handling the scoping directly. But I will probably take this approach at least part of the time.