gpt4 book ai didi

ruby-on-rails - 表单中的第一个参数不能包含 nil 或为空 Hartl's Rails 4 Tutorial

转载 作者:行者123 更新时间:2023-12-03 07:08:37 26 4
gpt4 key购买 nike

我正在学习 Michael Hartl 的 Rails 教程,并且在第 7.3.3 节中遇到了问题。我收到此错误消息:

ArgumentError in Users#new
Showing /Users/Anuraag/rails_projects/sample_app/app/views/users/new.html.erb where line #6 raised:
First argument in form cannot contain nil or be empty

当我运行以下 rspec 时:

bundle exec rspec spec/requests/user_pages_spec.rb -e "signup with invalid information"

在下面一行:

<%= form_for(@user) do |f| %>

这是我的代码。如果我没有很好地构建这个问题,请告诉我应该如何改进这个问题:我对 StackOverflow 也很陌生

app/views/users/new.html.erb:

<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>

<div class="row">
<div class="span6 offset3">
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages' %>

<%= f.label :name %>
<%= f.text_field :name %>

<%= f.label :email %>
<%= f.text_field :email %>

<%= f.label :password %>
<%= f.password_field :password %>

<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation %>

<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>

应用程序/ Assets / Controller /users_controller.rb:

class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end

def create
@user = User.new(user_params)
if @user.save
# Handle a successful save.
else
render 'new'
end
end

private

def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end

规范/请求/user_pages_spec.rb

require 'spec_helper'

describe "User pages" do

subject { page }

describe "signup page" do
before { visit signup_path }

it { should have_content('Sign up') }
it { should have_title(full_title('Sign up')) }
end

describe "profile page" do
let(:user) { FactoryGirl.create(:user) }
before { visit user_path(user) }

it { should have_content(user.name) }
it { should have_title(user.name) }
end

describe "signup" do

before { visit signup_path }

let(:submit) { "Create my account" }

describe "with invalid information" do
it "should not create a user" do
expect { click_button submit }.not_to change(User, :count)
end
end

describe "with valid information" do
before do
fill_in "Name", with: "Example User"
fill_in "Email", with: "user@example.com"
fill_in "Password", with: "foobar"
fill_in "Confirmation", with: "foobar"
end

it "should create a user" do
expect { click_button submit }.to change(User, :count).by(1)
end
end
end
end

最佳答案

在您的 new.html.erb 中,您已指定 form_for(@user) 这意味着您需要在实例变量 @user 中拥有一些值code> 在调用 new 操作之前。

您可以通过两种方式做到这一点:

一种方法是在 Controller 中定义一个操作 new,该操作将在渲染 new.html.erb 布局之前调用。例如:

def new
@user = User.new
end

另一种方法是在表单本身中您可以指定类似的内容

<%= form_for(User.new) do |f| %>

new 操作中定义它是更标准的方法。

关于ruby-on-rails - 表单中的第一个参数不能包含 nil 或为空 Hartl's Rails 4 Tutorial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21804050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com