ruby on rails - How to modify params before creating an object -
i'm using nested attributes create photo
, comment
object. set author on comment, nested inside photo.
here params:
photo: { file: 'hi.jpg', comments_params: [ { content: "hello world!" } ] }
but add author comment.
# ... comments_params: [ { content: "hello world!", author: current_user } ] # ...
what's easiest way this? controller code looks this.
@photo = photo.new(photo_params) @photo.save! private def photo_params params.require(:photo).permit(:file, comments_attributes: [:content]) end
i can manipulating params after filtering them strong_parameters
(pseudo-code, idea stands), rather not.
photo_params[:comments_attributes].each |comment| comment[:author] = current_user end
but feels bit wrong.
instead of messing params, assign author now-existing objects:
@photo = photo.new(photo_params) @photo.comments.select(&:new_record?).each {|c| c.author = current_user } @photo.save!
Comments
Post a Comment