此問題提出類似的問題: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_id
和user_id
字段。
非常感謝。