I am working on a new product that's a bit more complicated than our prior releases. Getting refamiliarized with nested parameters in Rails has been interesting. In this case imagine I have a discussion that, when creating it I also want to create the first comment. The discussion information is in a form with a nested form for the comment. So at the base you have these permitted parameters:
params.require(:discussion).permit(:title, comments_attributes: [:body])
That is fine, but I wanted to assure that the discussion and comment couldn't be messed with and would always be associated with the logged in, current_user
.
Stack Overflow told me this would be pretty straightforward these days.
Unfortunately that didn't work for me.
Perhaps I'm doing something wrong, but I had to get a little more…into it.
def discussion_params
_discussion_params = params.require(:discussion).permit(:title, comments_attributes: [:body])
_discussion_params.reverse_merge!(user_id: current_user.id)
_discussion_params[:comments_attributes].each do |key, value|
_discussion_params[:comments_attributes][key] = value.reverse_merge(user_id: current_user.id)
end
_discussion_params
end
I'd be happy to hear that there's an easier way.