ruby-on-rails - 不同控制器方法的强参数
问题描述
我正在 Rails 中创建一个控制器,我正在寻找方法为不同的控制器方法提供不同的强参数
在更新和新操作中,我想要求post
params.require(:post).permit(:body, :is_public, :title, :id)
但是在 中post/index
,我不需要这些参数。
您如何为不同的控制器方法制作不同的强参数?
解决方案
您的“强参数方法”只是 Ruby 方法。你可以有多少你想要的。
class PostsController < ApplicationController
def create
@post = Post.new(create_params)
end
def update
@post = Post.find(params[:id])
if @post.update(update_params)
# ...
else
# ...
end
end
private
def base_params
params.require(:post)
end
# Don't take IDs from the user for assignment!
def update_params
base_params.permit(:body, :title)
end
def create_params
base_params.permit(:body, :title, :foo, :bar)
end
end
您也可以随意命名它们。调用它[resource_name]_params
只是一个脚手架约定。
推荐阅读
- javascript - 平移或缩放时获取地图的纬度
- python - 快速检查列表中的子目录
- amazon-elastic-beanstalk - 如何将弹性 beantalk 经典负载均衡器转换为正在运行的应用程序上的应用程序负载均衡器?
- python - 某些结果后索引超出范围
- c# - Unity Streaming Assets iOS 不工作
- wordpress - 输入数量的产品页面的 URL - WooCommerce
- sql-server - 在 SSRS 2012 中导出为 CSV 时如何创建标题
- mongodb - 时刻js没有在猫鼬中更新
- angular - 有没有办法在图像路径中使用 angular base href 作为变量?
- python - 使用 selenium python 和 Firefox 重新打开相同的浏览器窗口