我对编程完全陌生,而且我遇到了麻烦。大约10天前,我开始了由Richard主持的关于ureddit.com的UT课程。到目前为止一切都进行得很顺利,但我第五周就有麻烦了。如果我没有使用正确的术语,你得原谅我,因为它已经被采纳了很多。
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抱歉,如果这是长篇大论。我很感谢你的帮助。
发布于 2013-11-03 17:24:55
应该是<%= @products.name %>
发布于 2013-11-03 19:06:34
/app/view/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)
endhttps://stackoverflow.com/questions/19755702
复制相似问题