0

我对编程完全陌生,我遇到了麻烦。大约 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

对不起,如果这是冗长的。我很感激任何帮助。

4

2 回答 2

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
于 2013-11-03T19:06:34.510 回答
0

它应该是<%= @products.name %>

于 2013-11-03T17:24:55.207 回答