【问题标题】:undefined method `title' for nil:NilClass Agile Web Development with Railsnil 的未定义方法“标题”:使用 Rails 进行 NilClass 敏捷 Web 开发
【发布时间】:2013-07-22 00:24:04
【问题描述】:

您好,我正在尝试从《Agile Web Development with Rails》一书中学习 RoR,但出现此错误:

undefined method `title' for nil:NilClass

    <ul>
        <% @cart.line_items.each do |item| %>
          <li><%= item.quantity %> &times; <%= item.product.title %></li>
        <% end %>
      </ul>
    app/views/carts/show.html.erb:4:in `block in _app_views_carts_show_html_erb___3275084074491266306_70111742218200'
    app/views/carts/show.html.erb:3:in `_app_views_carts_show_html_erb___3275084074491266306_70111742218200'

这是产品型号:

class Product < ActiveRecord::Base
    default_scope :order => 'title'
    has_many :line_items
    before_destroy :ensure_not_referenced_by_any_line_item
    validates :title, :description, :image_url, :presence => true
    validates :title, :uniqueness => true
    validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
    validates :image_url, :format => {:with => %r{\.(gif|jpg|png)}i,:message => 'musí jít o adresu URL pro obrázek typu GIF, JPG, nebo PNG.'
    }
    private
    def ensure_not_referenced_by_any_line_item
      if line_items.empty?
        return true
      else
        errors.add(:base, 'Existují položky')
        return false
      end
    end
end

line_items_controller:

 def create
    @cart = current_cart
        product = Product.find(params[:product_id])
        @line_item = @cart.add_product(product.id)

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

购物车型号:

class Cart < ActiveRecord::Base
  has_many :line_items, :dependent => :destroy

  def add_product(product_id)
    current_item = line_items.find_by_product_id(product_id)
    if current_item
      current_item.quantity = current_item.quantity.to_i + 1
    else
     current_item = line_items.build(:product_id => product_id)
    end
    current_item
  end
end

我正在使用 Ruby 2.0.0p247 和 Rails 4。 谢谢你的回答。

【问题讨论】:

  • 你的班级 LineItem 有 belongs_to :product 吗?
  • @SteveTurczyn 是的 > class LineItem

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


【解决方案1】:

这可能是因为购物车商品模型没有保存 product_id。

1) 首先,为 LineItem 模型添加验证。它不会解决问题,但您可以确定问题与 product_id 有关。

validates :product_id, presence: true

2a) 更新控制器以使用 Rails 4 强参数: http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

2b) 或者在学习 Ruby On Rails 的同时使用 Rails 3。

更新。

您还应该使用 rails 控制台从数据库中删除以前的 LineItem 记录,否则您仍然会看到此错误,因为旧 LineItems 未与 Product 关联。

【讨论】:

  • 你能告诉我如何删除记录吗?
  • @Nenor 运行 rails 控制台(“rails c”)并销毁记录(“LineItem.destroy_all”)
  • 我销毁了数据库中的记录,将 add_product 重写为以前的版本,它现在可以工作了。非常感谢!我真的很高兴 Rails 拥有如此出色的社区。你们都非常有帮助。现在我会继续学习,再次感谢您。
【解决方案2】:

@gvalmon 是对的,但我建议尝试使用

validates :product, presence: true

我会至少将您的 add_product 代码更改为此

` def add_product(product_id, qty = 1)

current_item = line_items.where(product_id: product_id).find_or_initialize
current_item.quantity += qty
current_item.save
current_item

结束 `

附:不要忘记将 qty 默认值更改为 '0'

【讨论】:

  • @gvalmon 我添加了 validates :product_id, presence: true 但错误保持不变。我不知道如何处理强参数,所以我可能会降级到 Rails 3。
  • @Nenor,问题是你没有设置product_id(在数据库中)
  • 我确实有这个迁移类 CreateLineItems
  • 我重写了代码,这就是我得到的结果 > #<:relation::activerecord_relation_lineitem:0x007fd85f1011e0> 的未定义方法 `find_or_initialize' 提取的源代码(第 5 行附近):3 4 5 6 7 8 def add_product(product_id, quantity = 1) current_item = line_items.where(product_id: product_id).find_or_initialize current_item.quantity += quantity current_item.save current_item
  • 好的,我的错误不是 find_or_initialize 而是 first_or_initialize 。它​​来自 rails 4。如果它不起作用,那么您应该为您的 rails 版本找到所需的方法。或者可以试试line_items.where(product_id: product_id).first || line_items.where(product_id: product_id).create
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多