2013-06-22 64 views
0

此問題提出類似的問題:Rails: Has and belongs to many (HABTM) -- create association without creating other records但我是Rails的新手,並將其應用於我的問題。HABTM filter_or_create usage

我可以創建一個新Location以及用戶和位置之間`一個新的關聯容易:

@location = Location.new(params[:location].merge(:user_ids => current_user.id)) 

我怎樣才能改變這種狀況:

  • Location和關聯,如果創建Location不存在
  • 如果Location已存在,則會創建一個新關聯

我的模型是這樣的:

Location

class Location < ActiveRecord::Base 
    attr_accessible :name, :user_ids 
    has_and_belongs_to_many :users 
end 

User

class User < ActiveRecord::Base 
    attr_accessible :email, :password, :password_confirmation, :remember_me 
    has_and_belongs_to_many :locations 
end 

所以我想知道如何創建只是一個關聯,以及如何檢查是否我應該創建一個關聯。

我的關聯表只有location_iduser_id字段。

非常感謝。

回答