Search code examples
ruby-on-railsrubystrong-parameters

How to modify params before creating an object


I'm using nested attributes to create a Photo and a Comment object. I would like to set the author on the comment, which is nested inside the photo.

Here are the params:

photo: {
  file: 'hi.jpg',
  comments_params: [
    { content: "hello world!" }
  ]
}

But I would like to add the author to the comment.

  # ...
  comments_params: [
    { content: "hello world!", author: current_user }
  ]
  # ...

What's easiest way to do this? My controller code looks like this.

@photo = Photo.new(photo_params)
@photo.save!

private

def photo_params
  params.require(:photo).permit(:file, comments_attributes: [:content])
end

I can do it by manipulating the params after filtering them with strong_parameters (pseudo-code, but the idea stands), but I would rather not.

photo_params[:comments_attributes].each do |comment|
  comment[:author] = current_user
end

But this feels a bit wrong.


Solution

  • Instead of messing with params, you could assign author to now-existing objects:

    @photo = Photo.new(photo_params)
    @photo.comments.select(&:new_record?).each {|c| c.author = current_user }
    @photo.save!