現在のコード(望んだ動きはします。)
ruby
1# Post 2class Post 3 belongs_to :category 4end 5 6# Category 7class Category 8 has_many :posts 9end 10 11# PostController 12def index 13 @posts = Post.all.order(created_at: :desc) 14end 15 16def by_categories 17 post_ids = Category.where(id: [1,2,3]).map{ |c| c.posts.ids }.flatten 18 @posts = Post.where(id: post_ids).order(created_at: :desc) 19 render :index # indexと同じレイアウト使用 20end
View側でindex
と同じレイアウトを使用したいと考えています。
ですので、whereした親レコード(categories
)と関係している複数の子レコード(posts
)を
class Post
をwhere
で取得した時と同じ形で取得したいと考えています。
mapでわざわざidを取得しているところや、そのidでまた検索しているところ等、
現在のコードは無駄な事をしている気がします。
良い方法はないでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。