activerecord - Rails model associations, has_many :through and has_one with the same model -
i have 2 models: user , state. state model has records each of 50 states in united states.
i each user have 2 attributes: 1 "home" state, , many states "visit".
i know have set sort of model associations achieve this, not sure when best approach is.
here's have far, know there must wrong have has_many , has_one association same model.
#user.rb class user < activerecord::base has_many :visits has_many :states, :through => :visits has_one :state end #visit.rb class visit < activerecord::base belongs_to :user belongs_to :state end #state.rb class state < activerecord::base has many :visits has many :users, :through => :visits belongs_to :user end
any suggestions?
you can't have has_many , has_one relationship on single model, in case state. 1 solution to:
create static model of states, not need database model, static variable on state model: us_states = {'1' => 'ak', '2' => 'al', etc}
or use fixtures load table of states database (more complicated because need use rake task or db:seed task load fixtures db, nice because can use active record manage model).
then can provide home_state_id on user model defines home_state , visits join between user_id , state_id.
Comments
Post a Comment