为什么当我访问“新"数据库时会自动创建数据库条目?页? [英] Why are database entries being automatically created when I visit the "new" page?
问题描述
当我访问新"页面时,我无法理解为什么我的应用会自动在数据库中创建条目.该页面应该有一个表单,当提交时,仅然后在数据库 (SQLite3) 中创建条目.
I'm having trouble understanding why my app is automatically creating entries in the database when I visit the "new" page. The page is supposed to have a form that, when submitted, then and only then creates entries in the database (SQLite3).
控制器:
class RecipeController < ApplicationController
def index
@recipes = Recipe.all
end
def new
@recipe = Recipe.create(params[:recipe])
if @recipe.save
redirect_to recipe_new_path
else
reload_page
end
end
def create
@recipe = Recipe.new
end
def show
end
def update
end
def destroy
end
private
def recipe_params
recipe_params = params.require(:recipes)
end
end
视图:
<!DOCTYPE html>
<html>
<body>
<h1>Add a recipe</h1>
<%= form_for @recipe do |f| %>
<%= f.label :name, "Recipe Name:" %>
<%= f.text_field :name %>
<br>
<%= f.label :recipe, "Recipe Description:" %>
<%= f.text_field :recipe %>
<br>
<%= f.submit %>
<% end %>
</body>
</html>
路由文件:
Rails.application.routes.draw do
get 'recipe' => 'recipe#index'
get 'recipe/new' => 'recipe#new'
post 'recipe/create' => 'recipe#create'
post 'recipes' => 'recipe#create'
resources :recipes
get 'recipe/:id' => 'recipe#show'
get 'recipe/update' => 'recipe#update'
get 'recipe/destroy' => 'recipe#destroy'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
推荐答案
在控制器中,创建 Recipe 的逻辑已在 new 方法中编写,并且仅在 create 方法中初始化了一个 recipe.但是在路由中,create 方法有一个 POST 调用(带有数据的表单提交),而新方法是一个 GET.
In the controller, the logic to create a Recipe has been written in new method and just a recipe is just initialized in create method. But in the routes the create method has a POST call(form submission with data) and the new method is a GET.
所以您需要做的就是将create"方法的名称更改为new"并在控制器中将new"方法的名称更改为create".
So all you need to do is just change the name of the 'create' method as 'new' and change the name of the 'new' method as 'create' in your controller.
即)
def create
@recipe = Recipe.create(params[:recipe])
if @recipe.save
redirect_to recipe_new_path
else
reload_page
end
end
def new
@recipe = Recipe.new
end
这会起作用.
这篇关于为什么当我访问“新"数据库时会自动创建数据库条目?页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!