访问视图页出现param缺失错误,求保留require(:restaurant)的解决方案
require(:restaurant) Let's break down what's going on here and fix it without ditching that important require(:restaurant) check.
The Root Cause
Your error pops up when visiting the /restaurants/new page, and it's all because of how your new action is written:
def new @restaurant = Restaurant.new(params.permit(:name, :address, :category)) end
When you load the new page, you're sending a GET request—there's no form submission data attached, so params[:restaurant] doesn't exist at all. On top of that, you're trying to pull top-level params like :name that aren't even present in this request. This step is totally unnecessary and conflicts with your strong parameter setup.
The Simple Fix
Update your new action to just initialize an empty Restaurant instance—you don't need to pass any params here:
def new @restaurant = Restaurant.new end
Why This Works (And Preserves require(:restaurant))
- When you visit the new page,
simple_form_for(@restaurant)will automatically generate a form that wraps all input fields under therestaurantnamespace. When the user submits the form via POST, Rails will package all form data intoparams[:restaurant]—exactly what yourrestaurant_paramsmethod is looking for. - Your
restaurant_paramsmethod'srequire(:restaurant)is a critical security check for the form submission POST request. It ensures that the request includes the wrapped restaurant data, preventing mass assignment vulnerabilities. This check stays fully functional with the fixednewaction.
After making this change, the new page will load without errors, and your create action will still safely validate that the required restaurant parameter is present with only the permitted fields.
内容的提问来源于stack exchange,提问作者Julie

