我是Rails的新手,已開始按照「敏捷Web開發和Rails:第四版」的方式工作。我目前在購物車創建章節。我主要複製了本書中的代碼,但是我的數據庫被稱爲'dvds'而不是'products'(因爲我正在爲一個項目創建一個DVD存儲)。使用Rails進行敏捷Web開發 - ActiveRecord :: StatementInvalid錯誤
我已經達到了章的末尾,當我運行的功能測試,我發現了以下錯誤:
test_should_destroy_dvd(DvdsControllerTest):
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: line_items.dvd_id: SELECT COUNT(*) FROM "line_items" WHERE ("line_items".dvd_id = 980190962)
app/models/dvd.rb:26:in `ensure_not_referenced_by_any_line_item'
app/controllers/dvds_controller.rb:76:in `destroy'
test/functional/dvds_controller_test.rb:50:in `test_should_destroy_dvd'
test/functional/dvds_controller_test.rb:49:in `test_should_destroy_dvd'
這裏是從它的引用dvd.rb文件中的代碼:
has_many :line_items
before_destroy :ensure_not_referenced_by_any_line_item
...
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
從dvds_controller.rb代碼:
def destroy
@dvd = Dvd.find(params[:id])
@dvd.destroy
respond_to do |format|
format.html { redirect_to(dvds_url) }
format.xml { head :ok }
end
end
而且從dvds_controller_test.r代碼b:
test "should destroy dvd" do
assert_difference('Dvd.count', -1) do
delete :destroy, :id => @dvd.to_param
end
assert_redirected_to dvds_path
end
本質上,我不明白錯誤,我正在尋找幫助,使它消失!我猜測問題是「沒有這樣的列:line_items.dvd_id」,但我不知道如何修改它。我已經融化了我的大腦,試圖找出它,所以任何幫助都將非常感激。
編輯: 這似乎是問題的所在,在create_line_items.rb:
class CreateLineItems < ActiveRecord::Migration
def self.up
create_table :line_items do |t|
t.integer :product_id
t.integer :cart_id
t.timestamps
end
end
def self.down
drop_table :line_items
end
end
而且,這裏的scehma:
ActiveRecord::Schema.define(:version => 20111125123848) do
create_table "carts", :force => true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "dvds", :force => true do |t|
t.string "title"
t.text "description"
t.string "image_url"
t.decimal "price", :precision => 8, :scale => 2
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "line_items", :force => true do |t|
t.integer "product_id"
t.integer "cart_id"
t.datetime "created_at"
t.datetime "updated_at"
end
end
啊,我試着rename_column看看它是否能解決問題。 (爲了清楚起見,我將上面的代碼改回原來的形式) 所以你說得對,我的問題是我有一個product_id列而不是dvd_id列。我怎樣才能解決這個問題? – Bobski
您需要創建另一個具有rename_column的遷移。然後重新運行rake db:migrate – ramblex
我使用了add_column,它似乎已經工作。謝謝 – Bobski