在定义方法时,我无法从另一个模型访问关联模型。在关联对象(line_item)中尝试访问对象attibute(大小的'price'属性)时,我收到以下错误。以下是我的代码和错误:
class LineItem < ActiveRecord::Base
attr_accessible :cart_id, :product_id, :quantity, :unit_price, :product, :cart, :color_id, :size_id, :extra_id, :color, :size, :extra
belongs_to :cart
belongs_to :product
has_one :color
has_one :size
has_one :extra
validates :quantity, :presence => true
def item_price
if size.price.nil? || size.price == 0
if extra.price.nil? || extra.price ==0
product.price
else
product.price + extra.price
end
else
if extra.price.nil? || extra.price == 0
product.price + size.price
else
product.price + size.price + extra.price
end
end
end
def full_price
unit_price * quantity
end
end
class Size < ActiveRecord::Base
attr_accessible :name, :price, :product_id, :line_item_id
belongs_to :product
belongs_to :line_item
def size_display
"#{name} +#{price}"
end
end
class LineItemsController < ApplicationController
def new
@line_item = LineItem.new
end
def create
@line_item = LineItem.create!(params[:line_item].merge(:cart => current_cart))
@line_item.update_attributes!(:unit_price => @line_item.item_price)
redirect_to current_cart_url
end
end
NoMethodError at /line_items
undefined method `price' for nil:NilClass
LineItem#item_price
app/models/line_item.rb, line 10
LineItemsController#create
app/controllers/line_items_controller.rb, line 7
有任何见解。
通过分析我的请求参数,我的大小对象似乎没有结果,可能是什么导致了这个?
1.9.3-p125 :008 > debugAttempt = LineItem.first
LineItem Load (0.9ms) SELECT "line_items".* FROM "line_items" LIMIT 1
=> #<LineItem id: 1, unit_price: nil, product_id: 1, cart_id: 1, color_id: 1, size_id: 2, extra_id: nil, quantity: 2, created_at: "2013-06-25 03:41:27", updated_at: "2013-06-25 03:41:27">
1.9.3-p125 :009 > debugAttempt.size
Size Load (0.3ms) SELECT "sizes".* FROM "sizes" WHERE "sizes"."line_item_id" = 1 LIMIT 1
=> nil
1.9.3-p125 :010 > debugAttempt.size_id
=> 2
1.9.3-p125 :015 > Size.find(debugAttempt.size_id).price.round
Size Load (0.6ms) SELECT "sizes".* FROM "sizes" WHERE "sizes"."id" = $1 LIMIT 1 [["id", 2]]
=> 50
所以基本上大小不是nil而是我找不到从lineItem对象访问相关大小的对象。我只能访问size_id。
关于如何解决这个问题的任何想法?
答案 0 :(得分:0)
由于您的LineItem
has_one Size
,外键应位于您的sizes
表格中。因此,您应该使用Size.find_by_line_item_id(debugAttempt.id)
进行调试,如果结果为nil
,则相关记录在db中不存在。