本文介绍了Rails4 //追加strong_parameters与其他PARAMS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,以下操作控制器:
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 ?
推荐答案
PARAMS
是ActionController的::参数,它继承了哈希一个实例。你可以用它做什么,你可能与任何散列:
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)
或者
post_params[:user_id] = current_user.id
@post = Post.create(post_params)
这篇关于Rails4 //追加strong_parameters与其他PARAMS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!