nil的未定义方法:视图和模型关系的NilClass

时间:2013-12-24 02:13:26

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

我有一个非常基本的应用程序,包括属于商店的商店和产品。我从产品表单中提取了商店ID,但每次尝试在产品视图中显示商店中的属性时,我都会收到未定义的方法错误。

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
      @stores = Store.all


    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(:name, :description, :imageurl, :url, :price, :Store_id, store_attributes: [:id, :name, :description])
      end
  end

product.rb

    class Product < ActiveRecord::Base

        belongs_to :store
                    has_many :pins
        validates_presence_of :name, :url, :price

    end

产品表单(_form.html.erb)

      <%= form_for(@product) do |f| %>
      <% if @product.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>

        <ul>
        <% @product.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
        </ul>
      </div>
    <% end %>

    <div class="form-group">
      <%= f.label :name, "Name" %>
      <%= f.text_field :name, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :description, "Description" %>
      <%= f.text_area :description, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :imageurl, "Image" %>
      <%= f.text_field :imageurl, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :url, "Web Address" %>
      <%= f.text_field :url, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :price, "Price" %>
      $<%= f.text_field :price, class: "form-control" %>
    </div>

  <div class="form-group">
  <%= collection_select(:product, :Store_id, Store.all, :id, :name, {:prompt=> "Select A Store"}, {:class => "form-control"} ) %>



  </div>
  <div class="form-group">
       <%= f.submit class: "btn btn-primary" %>
    </div>
  <% end %>

  <%= params.inspect %>

store.rb

     class Store < ActiveRecord::Base

has_many :products
has_many :pins, through: :products
accepts_nested_attributes_for :products, :allow_destroy => true

    end

违规产品视图(nil:NilClass的未定义方法`name'):

    <p id="notice"><%= notice %></p>

    <p>
      <strong>Name:</strong>
      <%= @product.name %>
    </p>

    <p>
      <strong>Description:</strong>
      <%= @product.description %>
    </p>

    <p>
      <strong>Store Id:</strong>
      <%= @product.Store_id %>
    </p>

    <p>
      <strong>Store Name:</strong>
      <%= @product.store.name %>
    </p>


    <p>
      <strong>Image:</strong>
      <%= @product.imageurl %>
    </p>

    <p>
      <strong>Url:</strong>
      <%= @product.url %>
    </p>

    <p>
      <strong>Price:</strong>
      $<%= @product.price %>
    </p>

    <%= params.inspect %>

    <%= link_to 'Edit', edit_product_path(@product) %> |
    <%= link_to 'Back', products_path %>

使用Rails控制台查找属于我正在引用的商店的所有产品,这是我最终的结果:

        Store.find(2).products
          Store Load (0.2ms)  SELECT "stores".* FROM "stores" WHERE "stores"."id" = ? LIMIT 1  [["id", 2]]
          Product Load (0.4ms)  SELECT "products".* FROM "products" WHERE "products"."store_id" = ?  [[nil, 2]]
         => #<ActiveRecord::Associations::CollectionProxy [#<Product id: 4, name: "Test Product", description: "This is a test product", imageurl: "www.test.com/test.jpg", url: "www.test.com", price: #<BigDecimal:7fcd7ca620b0,'0.12E2',9(36)>, created_at: "2013-12-21 23:38:03", updated_at: "2013-12-21 23:38:03", Store_id: 2>, #<Product id: 5, name: "TEST", description: "TEST", imageurl: "", url: "www.ggooogle.com", price: #<BigDecimal:7fcd7ca61318,'0.12E2',9(36)>, created_at: "2013-12-24 01:27:10", updated_at: "2013-12-24 01:27:10", Store_id: 2>]> 
        2.0.0p247 :012 > 

以下是错误页面中的完整描述:

        app/views/products/show.html.erb:20:in `_app_views_products_show_html_erb___2944853465650674919_70211283450300'
        actionpack (4.0.1) lib/action_view/template.rb:143:in `block in render'
        activesupport (4.0.1) lib/active_support/notifications.rb:161:in `instrument'
        actionpack (4.0.1) lib/action_view/template.rb:141:in `render'
        actionpack (4.0.1) lib/action_view/renderer/template_renderer.rb:49:in `block (2 levels) in render_template'
        actionpack (4.0.1) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
        activesupport (4.0.1) lib/active_support/notifications.rb:159:in `block in instrument'
        activesupport (4.0.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
        activesupport (4.0.1) lib/active_support/notifications.rb:159:in `instrument'
        actionpack (4.0.1) lib/action_view/renderer/abstract_renderer.rb:38:in `instrument'
        actionpack (4.0.1) lib/action_view/renderer/template_renderer.rb:48:in `block in render_template'
        actionpack (4.0.1) lib/action_view/renderer/template_renderer.rb:56:in `render_with_layout'
        actionpack (4.0.1) lib/action_view/renderer/template_renderer.rb:47:in `render_template'
        actionpack (4.0.1) lib/action_view/renderer/template_renderer.rb:17:in `render'
        actionpack (4.0.1) lib/action_view/renderer/renderer.rb:42:in `render_template'
        actionpack (4.0.1) lib/action_view/renderer/renderer.rb:23:in `render'
        actionpack (4.0.1) lib/abstract_controller/rendering.rb:127:in `_render_template'
        actionpack (4.0.1) lib/action_controller/metal/streaming.rb:219:in `_render_template'
        actionpack (4.0.1) lib/abstract_controller/rendering.rb:120:in `render_to_body'
        actionpack (4.0.1) lib/action_controller/metal/rendering.rb:33:in `render_to_body'
        actionpack (4.0.1) lib/action_controller/metal/renderers.rb:26:in `render_to_body'
        actionpack (4.0.1) lib/abstract_controller/rendering.rb:97:in `render'
        actionpack (4.0.1) lib/action_controller/metal/rendering.rb:16:in `render'
        actionpack (4.0.1) lib/action_controller/metal/instrumentation.rb:41:in `block (2 levels) in render'
        activesupport (4.0.1) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
        /usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/benchmark.rb:296:in `realtime'
        activesupport (4.0.1) lib/active_support/core_ext/benchmark.rb:12:in `ms'
        actionpack (4.0.1) lib/action_controller/metal/instrumentation.rb:41:in `block in render'
        actionpack (4.0.1) lib/action_controller/metal/instrumentation.rb:84:in `cleanup_view_runtime'
        activerecord (4.0.1) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
        actionpack (4.0.1) lib/action_controller/metal/instrumentation.rb:40:in `render'
        actionpack (4.0.1) lib/action_controller/metal/implicit_render.rb:10:in `default_render'
        actionpack (4.0.1) lib/action_controller/metal/implicit_render.rb:5:in `send_action'
        actionpack (4.0.1) lib/abstract_controller/base.rb:189:in `process_action'
        actionpack (4.0.1) lib/action_controller/metal/rendering.rb:10:in `process_action'
        actionpack (4.0.1) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
        activesupport (4.0.1) lib/active_support/callbacks.rb:413:in `_run__50926827859438065__process_action__callbacks'
        activesupport (4.0.1) lib/active_support/callbacks.rb:80:in `run_callbacks'
        actionpack (4.0.1) lib/abstract_controller/callbacks.rb:17:in `process_action'
        actionpack (4.0.1) lib/action_controller/metal/rescue.rb:29:in `process_action'
        actionpack (4.0.1) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
        activesupport (4.0.1) lib/active_support/notifications.rb:159:in `block in instrument'
        activesupport (4.0.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
        activesupport (4.0.1) lib/active_support/notifications.rb:159:in `instrument'
        actionpack (4.0.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
        actionpack (4.0.1) lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
        activerecord (4.0.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
        actionpack (4.0.1) lib/abstract_controller/base.rb:136:in `process'
        actionpack (4.0.1) lib/abstract_controller/rendering.rb:44:in `process'
        actionpack (4.0.1) lib/action_controller/metal.rb:195:in `dispatch'
        actionpack (4.0.1) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
        actionpack (4.0.1) lib/action_controller/metal.rb:231:in `block in action'
        actionpack (4.0.1) lib/action_dispatch/routing/route_set.rb:80:in `call'
        actionpack (4.0.1) lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
        actionpack (4.0.1) lib/action_dispatch/routing/route_set.rb:48:in `call'
        actionpack (4.0.1) lib/action_dispatch/journey/router.rb:71:in `block in call'
        actionpack (4.0.1) lib/action_dispatch/journey/router.rb:59:in `each'
        actionpack (4.0.1) lib/action_dispatch/journey/router.rb:59:in `call'
        actionpack (4.0.1) lib/action_dispatch/routing/route_set.rb:680:in `call'
        warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
        warden (1.2.3) lib/warden/manager.rb:34:in `catch'
        warden (1.2.3) lib/warden/manager.rb:34:in `call'
        rack (1.5.2) lib/rack/etag.rb:23:in `call'
        rack (1.5.2) lib/rack/conditionalget.rb:25:in `call'
        rack (1.5.2) lib/rack/head.rb:11:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/flash.rb:241:in `call'
        rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
        rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/cookies.rb:486:in `call'
        activerecord (4.0.1) lib/active_record/query_cache.rb:36:in `call'
        activerecord (4.0.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call'
        activerecord (4.0.1) lib/active_record/migration.rb:369:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
        activesupport (4.0.1) lib/active_support/callbacks.rb:373:in `_run__448513151921752681__call__callbacks'
        activesupport (4.0.1) lib/active_support/callbacks.rb:80:in `run_callbacks'
        actionpack (4.0.1) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/reloader.rb:64:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
        railties (4.0.1) lib/rails/rack/logger.rb:38:in `call_app'
        railties (4.0.1) lib/rails/rack/logger.rb:20:in `block in call'
        activesupport (4.0.1) lib/active_support/tagged_logging.rb:67:in `block in tagged'
        activesupport (4.0.1) lib/active_support/tagged_logging.rb:25:in `tagged'
        activesupport (4.0.1) lib/active_support/tagged_logging.rb:67:in `tagged'
        railties (4.0.1) lib/rails/rack/logger.rb:20:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/request_id.rb:21:in `call'
        rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
        rack (1.5.2) lib/rack/runtime.rb:17:in `call'
        activesupport (4.0.1) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
        rack (1.5.2) lib/rack/lock.rb:17:in `call'
        actionpack (4.0.1) lib/action_dispatch/middleware/static.rb:64:in `call'
        rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
        railties (4.0.1) lib/rails/engine.rb:511:in `call'
        railties (4.0.1) lib/rails/application.rb:97:in `call'
        rack (1.5.2) lib/rack/lock.rb:17:in `call'
        rack (1.5.2) lib/rack/content_length.rb:14:in `call'
        rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
        /usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
        /usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
        /usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'

        Request

        Parameters:

        {"id"=>"6"}

1 个答案:

答案 0 :(得分:0)

belongs_to方法负责定义关联模型的方法。您已经说过Product belongs_to :store,因此Rails定义了store方法,该方法假定您拥有store_id属性。但是,如果您没有store_id属性,则表示您具有Store_id属性。因此@product.store评估为nil,您会收到错误。

相关问题