Theopap
Theopap

Reputation: 755

Rails: Loop through db objects according to model associations

I have two models post.rb and attachment.rb with the following associations:

class Attachment < ApplicationRecord
  belongs_to :post, optional: true
end

class Post < ApplicationRecord
  has_many :attachments, :dependent => :destroy
end

This is what I have inside the controller action where the view is:

 def results_search
    if params[:search]
      @attachment = Attachment.all
      @posts = Post.search(params[:search])
   end
 end

I'm trying to do this <% @posts.attachments.each do |post|%> but I'm getting the following error undefined method attachments' for #<Post::ActiveRecord_Relation:0x007fa673bef9d0>

I want to loop through all the results from the search (@posts) and show the results alongside the attachments that belong to each post. Each attachment has a post_id assigned to it. Any ideas how I can implement this?

Upvotes: 0

Views: 44

Answers (1)

jvillian
jvillian

Reputation: 20263

You're going to want to do something like:

@posts.each do |post|
  # do some stuff with post (show name, content, etc.)
  post.attachments.each do |attachment|
    # do stuff with attachment (show, etc.)
  end
end 

What it really looks like depends on where you're doing this (view?) and what tools you're using (vanilla erb, slim, haml, etc.).

Also, you're going to want to do some eager loading so you don't end up in N+1 land.

Upvotes: 4

Related Questions