ruby on rails - Getting duplications when listing records when using has_many :through -
i have 3 tables: manager, site , visit.
goal
i able create visits in way when find valid manager , valid site create valid visit.
problems
when tried simple has_many :though association got unexpected results(i haven't been using often).
i have set way:
class manager < activerecord::base has_many :sites, through: :visits has_many :visits end class site < activerecord::base has_many :managers, through: :visits has_many :visits end class visit < activerecord::base belongs_to :manager belongs_to :site end
the first problem have when find manager , site:
manager = manager.find(3) site = site.find(5)
and create 2 visits:
visit.create(manager: manager, site: site) visit.create(manager: manager, site: site)
i have 2 visits expected:
manager.visits.count #2 site.visits.count #2
but haven't expected , don't wont 2 sites manager:
manager.sites.count #2
i manager.sites return 1 site manager has visited 1 site:/
problem 2 can't figure out how set works way described. need model cant figure out.
am doing wrong here?
can me please?
maybe should add counter column visit
, , instead of creating new row each visit use x = visit.find_or_create_by(~manager, ~site); x.counter.increment; (in schema counter should default 0)
. define has_many :visits
each (or scopes), , access manager.visits.where(~search site).counter
, give total visits counter.
Comments
Post a Comment