2012-10-02 53 views
1

我有用戶,位置和關注,其中用戶have_many位置:through =>:如下。遵循belongs_to用戶和位置。我想在Follows表中添加一行 - 即在用戶和位置之間創建一個關係關係。如何在Ruby on Rails的中間關係中創建一行

我不知道如何做到這一點,或者如果我採取跟隨權:

class CreateFollows < ActiveRecord::Migration 
    def change 
    create_table :follows |do| t 
     t.references :user_id 
     t.references :location_id 
     t.timestamps 
    end 
    end 
end 

而且我嘗試使用添加的代碼遵循的關係,給用戶ID和locationid,是

newFollow = Follow.new(:user_id => userid, :location_id => locationid) 
newFollow.save 

我收到錯誤未知屬性:user_id。

有什麼想法?我很困難。非常感謝!

回答

4

在遷移過程中,references需要沒有_id的字段名稱,然後將其附加_id。現在,您正在創建兩列:user_id_idlocation_id_id

相反,這些線...

t.references :user_id 
t.references :location_id 

...你需要這些行:

t.references :user 
t.references :location 

一旦你已經固定的列名...

你不必在「通過」表中手動創建記錄。如果你有一個用戶,你有一個位置,你的協會是設置正確(has_many follows; has_many :locations, through: :follows),你可以簡單地使用

user.locations << location 

這將自動創建連接記錄。

+0

完成,對不起! – user1436111