Rails4 // append strong_parameters with other params

亡梦爱人 提交于 2019-12-13 06:59:10

问题


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)


来源:https://stackoverflow.com/questions/26517421/rails4-append-strong-parameters-with-other-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!