当前位置: 首页 > 知识库问答 >
问题:

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

范文昌
2023-03-14

我有一个非常基本的应用程序,由商店和属于商店的产品组成。我从产品表单中很好地提取了store ID,但每次尝试在产品视图中显示store中的属性时,都会出现未定义的方法错误。

products\u控制器。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的未定义方法“名称”):

    <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个答案

水渊
2023-03-14

属于方法负责定义关联模型的方法。您已经说过产品属于:store,所以Rails定义了一个store方法,该方法假设您有一个store id属性。但是,您没有store\u id属性,您有store\u id属性。所以产品。store的计算结果为nil,您将得到所得到的错误。

 类似资料:
  • 我想用ruby制作一个康威的生活游戏版本。我创建了一个网格类,其中@play\u area作为实例变量。然而,当我运行代码时,@play\u area在经过两次求值后显示为nil(当在行中求值时,如果@play\u area[x\u mod][y\u mod].alive)。为什么会这样? 编辑 以下是初始化函数: 以下是发生错误的函数: 对@play_area中每个单元格的检查显示每个单元格都正

  • Rails关联的基本问题如下表: 商店:名称,网络 产品:标题、价格、店铺id 关系定义为has_many并属于: 型号: shop.rb 产品rb型 控制器: shops\u控制器。rb型 products_controller.rb 在商店视图中,我设法参考并显示每个商店的所有产品,没有问题: 但另一方面,在产品视图中,我无法从Shop表中显示网络信息: 这将返回以下错误:

  • 我正在学习Ruby,我有一个无法理解的bug。我有一个方法,它接受一个字符串(行)数组,并删除所有行,直到包含模式的某一行。该方法如下所示: 这工作正常,生成的字符串(行)正确显示在我正在生成的网页上。 此外,我想删除该模式后面的所有非空行。我修改了方法如下: 令人惊讶的是(至少对我来说)这不起作用。在生成的网页上,我看到的不是内容,而是错误消息:Liquid error:nil类的未定义方法“[

  • 大家好,我刚刚遇到了这个问题,我正在学习教程,我试图在我的文章和类别之间创建多对多关联,所以我通过键入以下内容添加了article\u类别模型: 在这个模型里面我输入了 内部文章。rb: 和内部类别。rb: 所以我去了控制台:通过输入以下内容进行关联: 我检查了文章。类别 我也试了分类 结果是: 所以我试图通过输入以下内容使这篇文章成为此类文章的一部分: 所以我得到了这个错误: 这是错误,伙计们,

  • 定义关联 关联在 Hyperf 模型类中以方法的形式呈现。如同 Hyperf 模型本身,关联也可以作为强大的 查询语句构造器 使用,提供了强大的链式调用和查询功能。例如,我们可以在 role 关联的链式调用中附加一个约束条件: $user->role()->where('level', 1)->get(); 一对一 一对一是最基本的关联关系。例如,一个 User 模型可能关联一个 Role 模型