Rails4 // append strong_parameters with other para

2019-08-30 01:50发布

问题:

Let's say for the following actions' controller:

class PostsController < ApplicationController

    def create
        @post = Post.create(post_params)
    end

    private
        def post_params
          params.require(:post).permit(:title, :content)
        end

end

Is there a one-line way to do something like this when creating a record :

def create
    @post = Post.create(post_params, user_id: current_user.id)
end

What would be the clean way to do it ? Is it possible ?

回答1:

params is an instance of ActionController::Parameters, which inherits from Hash. You can do anything with it that you might with any Hash:

@post = Post.create(post_params.merge user_id: current_user.id)

Or...

post_params[:user_id] = current_user.id
@post = Post.create(post_params)