2012-09-30 59 views
0

基本上,现在我有一个位置和一个用户,关系“跟随”。这两个都是has_and_belongs_to_many关系。我已经在数据库中创建了用户和位置,但是我想在用户决定跟随某个位置时连接这两个位置。我该如何去做呢?如何在rails中创建关系?

我想过使用LocationUser.new(..),其中LocationUser是位置&用户表或Location.create(...)或某事的连接表,但我不觉得任何一个那些正在做我想做的事。

非常感谢!

回答

0

连接表不应该有模型,也不应该有外键。在create_table迁移中设置id: false

然后,User.locations << Location.new或类似的。

0

您可以使用范围的additition(如果你不使用连接模式,真正的habtm):

current_user.locations << @location 

或范围的创建(如果你有一个连接模型):

current_user.location_users.create(:location_id => @location)