mercredi 31 décembre 2014

Querying a has_and_belongs_to_many association in Ruby

OK. What I am trying to achieve is based on generating a list of related articles based on a specific article and I want to get these related articles based on the categories that are associated with the article. I have a simple habtm relationship between these two models: article and category (join table is named articles_categories). I want to create a related articles query based on articles that have the same category_ids as one article. For example, article #1 is associated with category #1 and category #2. I want to write a query that grabs the category ids of article #1, then queries the article model for all articles that are associated with those same categories, category #1 and category #2. I have tried everything under the sun and can't seem to figure this out. I have tried .join statements of various kinds and nothing seems to work. I tried to break it down into two parts below:


I can grab all of the category ids of the specific article that I want to reference like this: article_cat_ids = @article.category_ids


The second part would be the article filter based on these category ids but I can't figure this part out.


So my question is, how do I get an array of articles that are associated with the category ids in the array article_cat_ids. And as a bonus kicker, I would love to exclude the specific article that I originally reference to create the article_cat_ids so that the list of articles does not include the article that I am trying to get related articles for.


Any help would be appreciated.


Aucun commentaire:

Enregistrer un commentaire