ruby on rails - How to use foreign key in model and form builder? -
i have 2 models: user
, location
below:
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
you can see use custom foreign_key models. use form builder build user sign form, when submit data error occurs:
location(#2170327880) expected, got string
i use simple_form
build form, related code is:
= f.input :location, :collection => location.all.collect {|c| [c.loc_name, c.loc_id]}
how can resolve problem? or must use default foreign_key location_id
association?
thanks.
update:
when rename location
field in user
model loc_id
, remove :foreign_key
this:
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
it works fine. still want know how associate user
, location
model.
p.s. use location
model store country code , country name, never update user
.
it sounds want have
class user < activerecord::base belongs_to :location end class location < activerecord::base has_many :users end
this means user has location_id
column. if things other way around (user_id column on location) given location can associated 1 user. rails way location_id
on users 'points' @ id column in locations table. if want point @ different column, use :primary_key
option (the :foreign_key
option if wanted column on users called other location_id)
in terms of form, can't f.select :location
- forms don't know how transfer complicated object that. in these cases want set form control location_id attribute, i.e.
= f.input :location_id, :collection => location.all.collect {|c| [c.loc_name, c.id]}
if go down route of having location id column refer loc_id column on location, you'd need change be
= f.input :location_id, :collection => location.all.collect {|c| [c.loc_name, c.loc_id]}
personally if you're starting out rails i'd stick defaults
Comments
Post a Comment