ProductsController #create中的NoMethodError

时间:2014-03-04 02:00:38

标签: ruby-on-rails ruby ruby-on-rails-4

我正在完成“使用Rails 4进行敏捷Web开发”,我在第7章,任务B:验证和单元测试中遇到了这个问题。任何帮助将不胜感激。

当我尝试添加新条目时,这是我得到的错误。


undefined method `titles' for #Product:0x007fa6fcbf28e0

提取的来源(第30行):

respond_to do |format|
  if @product.save
    format.html { redirect_to @product, notice: 'Product was successfully created.' }
    format.json { render action: 'show', status: :created, location: @product }
  else
     

如果@ product.save是第30行。


这是在 / rails / depot_a / app / models

中将这些行添加到 products.rb 之后开始的
    class Product < ActiveRecord::Base
validates :titles, :description, :image_url, presence: true
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
    with: %r{\.(gif|jpg|png)\Z}i,
    message: 'must be a URL for GIF, JPG, or PNG image.'
}
end

这是我在错误中提到的 / rails / depot_a / app / controllers 中的 products_controller.rb

   class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  # GET /products
  # GET /products.json
  def index
    @products = Product.all
  end

  # GET /products/1
  # GET /products/1.json
  def show
  end

  # GET /products/new
  def new
    @product = Product.new
  end

  # GET /products/1/edit
  def edit
  end

  # POST /products
  # POST /products.json
  def create
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render action: 'show', status: :created, location: @product }
      else
        format.html { render action: 'new' }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /products/1
  # PATCH/PUT /products/1.json
  def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /products/1
  # DELETE /products/1.json
  def destroy
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_product
      @product = Product.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def product_params
      params.require(:product).permit(:title, :description, :image_url, :price)
    end
end

ruby​​ 2.0.0p353

Rails 4.0.3

0 个答案:

没有答案