2011-09-30 21 views
1

我有兩個項目,用戶和帖子,以及將它們鏈接在一起的連接表。這兩個項目之間具有has_many關係(:通過連接表)。我在創建兩個數據庫後創建了連接表。我遇到的問題是我每次嘗試使用@ user.posts或@ post.users時都會遇到錯誤。這幾乎就像他們沒有正確設置。我正在閱讀的地方是,如果您在創建模型後創建關聯,那麼您必須使用add_column方法。這是我的問題嗎?我不確定如何實施該方法或任何其他方法。這是我得到的錯誤:連接表和has_many關係不起作用

SQLite3 :: SQLException:no such column:users.post_id:SELECT「users」。* FROM「users」WHERE「users」。「post_id」= 60 AND「users」。 id「=?限制1

看起來像我需要添加一個列的錯誤,但我不知道如何做到這一點。

這裏是我的最新schema.db:

ActiveRecord::Schema.define(:version => 20110930155455) do 

    create_table "posts", :force => true do |t| 
    t.text  "content" 
    t.integer "vote_count" 
    t.text  "author" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "user_id" 
    end 

    create_table "users", :force => true do |t| 
    t.string "user_name" 
    t.string "password" 
    t.date  "time" 
    t.integer "posts_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "post_id" 
    end 

    create_table "votes", :force => true do |t| 
    t.integer "post_id" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

end 
+1

您可以發佈當前模式中與表用戶,帖子和連接表有關的部分嗎?你可以在你的應用程序的'db/schema.rb'下找到它。類User',Post'和連接模型類的定義也是一樣(如果你有一個具體的類)。然後,我使用「has_many:through」關聯... – mliebelt

+0

發佈模型代碼和關於連接表的信息。您的用戶表不應該有post_id字段,同樣,posts表不應該有一個user_id字段。這些字段應該在連接表中。 –

回答

0

是的,你需要爲外鍵遷移。您需要將post_id添加到類型爲integer的users表中。執行

rails g migration AddPostIdToUsers post_id:integer 

生成您的遷移。您應該創建一個看起來像

class AddPostIdToUsers < ActiveRecord::Migration 
    def change 
    add_column :users, :post_id, :integer 
    end 
end 

您也可能要考慮建立一個*的has_many:通過聯想*,它會給你更多的控制。

+0

我正在使用:through關聯。這似乎沒有幫助。我似乎在更新表格時遇到問題。我意識到我在posts表中命名了一列,就像我的連接表一樣。我試圖改變名稱並運行rake db:migrate,但沒有任何反應。名稱不變。我不知道我是否正在創建這些關聯和東西,但實際上沒有更新? – user972276

+0

在這種情況下,您需要連接表中的FK,而不是User或Post。你連接表本質上屬於'belongs_to:user'和'belong_to:post'。然後執行'rake db:migrate',你會看到這些添加在'schema.db'中。您可以在軌道控制檯中使用關聯進行遊戲,並且可以檢查它是否正常工作。 –