force强参数值
force strong parameter value
如何从控制器手动插入参数值,
这是我的控制器
def new
@new_post = Post.new(params[:title])
end
def create
@new_post = Post.new(new_post_params)
if @new_post.save
flash[:success] = 'Post created!'
redirect_to home_url
else
flash[:danger] = @new_post.errors.full_messages.to_sentence
redirect_to home_url
end
end
private
def new_post_params
params.require(:post).permit(
:title,
poster_id: current_user.id,
poster_name: current_user.name
)
结束
我的表单视图是这样的
form_for @new_post do |f|
f.text_area :title
end
厌倦了使用这种方法,poster_id 和 poster_name 仍然是空白
def new_post_params
params.require(:post).permit(
:title,
poster_id: current_user.id,
poster_name: current_user.name
)
end
def new_post_params
params[:post][:poster_id] = current_user.id
params[:post][:poster_name] = current_user.name
params.require(:post).permit(
:title,
:poster_id,
:poster_name
)
end
试试这个
params.require(:post).permit(:title).merge(
{
poster_id: current_user.id,
poster_name: current_user.name
}
)
如何从控制器手动插入参数值, 这是我的控制器
def new
@new_post = Post.new(params[:title])
end
def create
@new_post = Post.new(new_post_params)
if @new_post.save
flash[:success] = 'Post created!'
redirect_to home_url
else
flash[:danger] = @new_post.errors.full_messages.to_sentence
redirect_to home_url
end
end
private
def new_post_params
params.require(:post).permit(
:title,
poster_id: current_user.id,
poster_name: current_user.name
)
结束
我的表单视图是这样的
form_for @new_post do |f|
f.text_area :title
end
厌倦了使用这种方法,poster_id 和 poster_name 仍然是空白
def new_post_params
params.require(:post).permit(
:title,
poster_id: current_user.id,
poster_name: current_user.name
)
end
def new_post_params
params[:post][:poster_id] = current_user.id
params[:post][:poster_name] = current_user.name
params.require(:post).permit(
:title,
:poster_id,
:poster_name
)
end
试试这个
params.require(:post).permit(:title).merge(
{
poster_id: current_user.id,
poster_name: current_user.name
}
)