我有兩個型號:User
和Location
如下:如何在模型和表單構建器中使用外鍵?
class User < ActiveRecord::Base
attr_accessible :location, :password, :user_name, :password_confirmation
validates :location, :user_name, :presence => true
validates :password, :presence => true, :confirmation => true
has_one :location, :foreign_key => 'location'
end
class Location < ActiveRecord::Base
attr_accessible :loc_id, :loc_name
belongs_to :user, :foreign_key => 'loc_id'
end
你可以看到,我使用自定義foreign_key的車型。我使用表單生成器來構建一個用戶註冊的形式,但是當我提交的數據出現錯誤:
Location(#2170327880) expected, got String
我用simple_form
構建表單,相關的代碼是:
= f.input :location, :collection => Location.all.collect {|c| [c.loc_name, c.loc_id]}
我怎麼能解決這個問題?或者我必須使用默認foreign_key,如location_id
用於關聯?
謝謝。
更新:
當我在User
模型重命名location
領域loc_id
並刪除:foreign_key
這樣的:
class User < ActiveRecord::Base
attr_accessible :loc_id, :password, :user_name, :password_confirmation
validates :loc_id, :user_name, :presence => true
validates :password, :presence => true, :confirmation => true
has_one :location, :foreign_key => 'location'
end
class Location < ActiveRecord::Base
attr_accessible :loc_id, :loc_name
belongs_to :user
end
它工作正常。但我仍然想知道如何關聯User
和Location
模型。
P.S.我使用Location
模型來存儲國家代碼和國家名稱,這將永遠不會被User
更新。
多個用戶可以擁有相同的位置? –
是的。 'location'表是一個靜態數據表。我將把所有的城市都保存在桌子上,並給它一個唯一的ID。在用戶表中,我將保存城市ID而不是城市名稱。 – zhu0qun