# \[MongoId\]\[query\] - relazione n -\> n tra Hastag & Post devo estrarre gli hastag con piu post

**URL:** <https://www.ruby-forum.com/t/mongoid-query-relazione-n-n-tra-hastag-post-devo-estrarre-gli-hastag-con-piu-post/236792>\
**Category:** IT\
**Created:** [October 3, 2013, 10:30am UTC](https://www.ruby-forum.com/t/mongoid-query-relazione-n-n-tra-hastag-post-devo-estrarre-gli-hastag-con-piu-post/236792 "2013-10-03T10:30:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alcina](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a587f6/32.png) [@alcina](https://www.ruby-forum.com/u/alcina)\
**Post date:** [October 3, 2013, 10:30am UTC](https://www.ruby-forum.com/t/mongoid-query-relazione-n-n-tra-hastag-post-devo-estrarre-gli-hastag-con-piu-post/236792/1 "2013-10-03T10:30:13Z")

</div>

Ciao a tutti mi trovo davanti a questo problema, oramai da due giorni,  
ho necessita di estrarre gli hashtag più utilizzati:

Model :

- Hashtag
- Post

Relation:

- n -\> n

in hahtag cè un campo post\_ids che contiene tutti gli id dei post.  
io devo estrarre gli hashtag più utilizzati, ovvero quelli che nel campo  
post\_ids hanno piu id.

come posso fare ??  
grazie.

---

<div class="post-metadata">

**Author:** ![rsaccon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a5b964/32.png) [@rsaccon](https://www.ruby-forum.com/u/rsaccon)\
**Post date:** [October 15, 2013, 4:11pm UTC](https://www.ruby-forum.com/t/mongoid-query-relazione-n-n-tra-hastag-post-devo-estrarre-gli-hastag-con-piu-post/236792/2 "2013-10-15T16:11:15Z")

</div>

Ho risolto in questo modo;

after\_create :associate\_hashtags\_if\_group\_post

def associate\_hashtags\_if\_group\_post  
if group\_id?  
self.group.hashtag\_ids.each do |h|  
if (hashtag = Hashtag.where(:id =\> h))  
hashtags \<\< hashtag  
end

```
  end
end

```

end

in questo modo ho sempre aggiornati i dati nella tabella hashtag, per  
poi fare un semplice order in visualizzazione.
