Pavel Sanatov Pavel Sanatov - 4 years ago 143
Ruby Question

How to auto-assign value to the permitted params in Rails controller create method

I have Ruby On Rails application. I have created method in my

CommentsController
and I want to always auto-assign value to one of the permitted fields (in my case its :commenter)"

class CommentsController < ApplicationController
def create
@meme = Meme.find(params[:meme_id])
@comment = @meme.comments.create(comment_params)
redirect_to meme_path(@meme)
end

private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end


How can I achieve this?

Answer Source

At first, you should authenticate a user. Since the current user is authenticated there is no need to pass him in parameters. You can do something like this:

class CommentsController < ApplicationController

  before_action :authenticate_user!

  def create
    @meme = Meme.find(params[:meme_id])
    @comment = @meme.comments.create(comment_params)

    redirect_to meme_path(@meme)
  end

private

    def comment_params
      params.require(:comment).permit(:body).merge(commenter: current_user)
    end
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download