ブログポストが複数カテゴリを持てるという場合で、 ある記事と同じカテゴリを持つ記事を探すということをやりたい。 #Postモデル class Post < ActiveRecord::Base has_and_belongs_to_many :categories end #交差テーブル class CategoriesPost < ActiveRecord::Base end #Categoryモデル class Category < ActiveRecord::Base has_and_belongs_to_many :posts end post = Post.first categories = Category.joins(:posts).where("posts.id = ?", post.id).select("categories.id") category_ids = c
![Railsでアソシエーションされたモデルを条件にして検索する](https://cdn-ak-scissors.b.st-hatena.com/image/square/e42e8094d7bb5fe980c3c9ed5ae04ae611667149/height=288;version=1;width=512/https%3A%2F%2Fworkabroad.jp%2Fassets%2Fogp%2Frails-ec58549f80b7073f28673874c1cdfeb26eaf7f613a14d7665d8e9cf5b06b10d9.jpg)