私は2つのモデルを持っています: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]}
この問題を解決するにはどうすればよいですか?または、関連付けにデフォルトの外部キーを使用する必要がありますlocation_id
か?
ありがとう。
アップデート:
モデルのlocation
フィールドの名前をに変更し、次のように削除すると、次のようになります。User
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
モデルを関連付ける方法を知りたいです。
PS私はLocation
モデルを使用して国コードと国名を保存しますが、これはによって更新されることはありませんUser
。