当我为用户创建脚手架时,我注意到在我的控制器的创建操作中,它列出了
@user = User.new(user_params)
并且实际上没有
@user.save
随处可见。但是,一切似乎都有效,新用户确实会保存到数据库中。为什么是这样?这个用户在哪里被保存,为什么他们使用.new而不是仅仅使用.create,这也会自动保存?
谢谢!
这是我的完整控制器:
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
@users = User.all
@portion = Portion.new
end
# GET /users/1
# GET /users/1.json
def show
@allusers = User.all
@rentbill = RentBill.last
end
# GET /users/new
def new
@user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:first_name, :last_name, :email_address, :admin, :pays_tv, :pays_internet)
end
end
答案 0 :(得分:0)
这是正确的行为:
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
它正在初始化一个新的用户对象然后响应。如果用户对象得到正确保存,则显示用户已成功创建&#39;否则显示错误消息并再次呈现新的用户表单。