我是编程新手,我遇到了麻烦。大约10天前,我在Richard Schneeman主持的ureddit.com上开始了UT-Rails课程。到目前为止它一直很顺利,但我在第5周遇到麻烦。如果我没有使用正确的术语,你将不得不原谅我,因为它有很多东西可以接受。
https://github.com/zkay/move_logic_to_controllers是我目前正在关注的教程。
我已完成第2步。我已将app/views/products/new.html.erb
中的文字替换为以下内容:
<%= form_for(@product) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :price %><br />
<%= f.text_field :price %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
然而,当我尝试按照教程添加新产品时,我得到的拒绝是:
NoMethodError in Products#create
Showing C:/Sites/move_logic_to_controllers/app/views/products/create.html.erb where line #3 raised:
undefined method `name' for nil:NilClass
Extracted source (around line #3):
1: <h2>Product Created Successfully<h2>
2:
3: <%= @product.name %> added to the website, it costs: $<%= @product.price %>
Rails.root: C:/Sites/move_logic_to_controllers
如果我删除.name
和.price
次调用,则该页面无效,但不会显示我提交的任何数据。
在app/controllers/product_controller.rb
我有以下内容:
class ProductsController < ApplicationController
def index
@products = Product.includes(:user).all
end
def new
@product = Product.new
end
respond_to do |format|
if @product.save
format.html { render :action => "create" }
format.json { render :json => @product }
else
format.html { render :action => "new" }
format.json { render :json => @product.errors, :status => :unprocessable_entity }
end
end
end
很抱歉,如果这是漫长的啰嗦。我感谢任何帮助。
答案 0 :(得分:0)
应为<%= @products.name %>
答案 1 :(得分:0)
/app/views/products/create.html.erb
您不想使用create.html.erb。
class ProductsController < ApplicationController
def index
@products = Product.includes(:user).all
end
def new
@product = Product.new
end
def create
@product = Product.new(params[:product])
if @product.save
redirect_to products_path, notice: "You added product"
else
flash[:error] = "Something wrong!"
render :new
end
end
end
如果使用Rails 4,请使用:
def create
@product = Product.new(product_params)
if @product.save
redirect_to products_path, notice: "You added product"
else
flash[:error] = "Something wrong!"
render :new
end
end
private
def product_params
params.require(:product).permit(:name, :price)
end