model :
cart.rb
class Cart < ActiveRecord::Base
attr_accessible :title, :body
has_many :line_items, dependent: :destroy
end
product.rb
class Product < ActiveRecord::Base
default_scope :order => 'title'
has_many :line_items
before_destroy :ensure_not_referenced_by_any_line_item
attr_accessible :description, :image_url, :price, :title
validates :title, :description, :image_url,:presence => true
validates :price,:numericality => {:greater_than_or_equal_to => 0.01}
validates :title,:uniqueness => true
validates :image_url,:format => {
:with =>%r{\.(gif|jpg|png)$}i,
:message =>'must be a url for GIF ,JPG OR PNG image_url'}
private
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base ,'line items present')
return false
end
end
line_item.rb
class LineItem < ActiveRecord::Base
attr_accessible :cart_id, :product_id,:quantity
belongs_to :Product
belongs_to :cart
end
controller
line_item_controller.rb 中的creat方法
def create
@cart = current_cart
product=Product.find(params[:product_id])
@line_item = @cart.line_items.build (这儿是第45行)
@line_item.product = product
respond_to do |format|
if @line_item.save
format.html { redirect_to(@line_item.cart,
:notice => 'line item was successfully created.')}
format.xml {render :xml => @line_item,
:status => :created ,:location => @line_item}
else
format.html {render :action => "new"}
format.xml {render :xml => @line_item.errors,
:status => :unprocessable_entity}
end
end
end
运行是出现 ActiveRecord::UnknownAttributeError in LineItemsController#create
unknown attribute: cart_id app/controllers/line_items_controller.rb:45:in `create'
我 google 了下 还是每搞懂哪儿错了。