i'm trying figure out association between 3 models have.
challenge, sip, user
user can create sip, , users can submit challenges sip; sips has many challenges
challenge.rb
class challenge < activerecord::base belongs_to :user belongs_to :sip, counter_cache: true end
sip.rb
class sip < activerecord::base belongs_to :user has_many :challenges end
user.rb
class user < activerecord::base has_many :challenges has_many :sips end
here columns:
challenge: id, user_id, sip_id sip: id, user_id user: id
in in sip view, i'm trying list of users this:
- @sip.each |sip| = sip.challenges.users.to_json
ultimately, want users have submitted challenges belongs sip
.
sip.challenges
collection, have map
on users. that's going collection of collections of users, flatten
it, , uniq
it, , compact
remove nil
s:
sip.challenges.map(&:user).flatten.uniq.compact
flatten
turns [[1,2], [2,3]]
[1,2,2,3]
, uniq
turns [1,2,3]
.
map(&:user)
sends user
each item in enumerable (collection) that's left of map
, in case, each challenge in challenges
.
is efficient? uh... left exercise you.
edit: add html tags: result of doing enumerable
, can each
on it:
%ul - sip.challenges.map(&:user).flatten.uniq.compact.each |user| %li= user
Comments
Post a Comment