Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails include all associated data in get all request

I am trying to get all records of a specific table with their associated data when called from the model. I've tried a number of different options but cant seem to figure it out.

I have a a rails structure where: (assume all classes are inheriting from activerecord:base)

class Post 
    has_many :image
    has many :comment 
end 

class Image 
    belongs_to :post
end

class Comment 
    belongs_to :post
end

Basically I want to get all the posts with all associated data in my Post class (or model). For example:

    Post.all (but then here do something to include each post's images and comments) 

I've tried these two options but they dont return the associated data

Post.all.eager_load(:image, :comment)
Blog2.all.includes(:image, :comment)

In my controller I have an index method

  def index
    @posts = Post.all
    render json: @posts, :include => [:image, :comment]
  end

this index method works perfectly and includes the associated data with each record but when I try to do get all posts with their associated data in the model i cant get to to work. thanks for the help

like image 412
Billy Avatar asked Mar 29 '16 02:03

Billy


1 Answers

You're close. The includes method will preload the associated data, but won't actually present it to you with the results unless you specifically tell it to.

For example:

blog_records = Blog2.all.includes(:image, :comment)
blog_records_with_associations = blog_records.map do |record|
  record.attributes.merge(
    'image' => record.image,
    'comment' => record.comment
  )
end

This will convert the data into an array of hashes, suitable for publishing as json.

If you just need to access the associated records in Ruby, it's simpler:

blog_records = Blog2.all.include(:image, :comment)
first_image = blog_records.image     # preloaded, no SQL fired
first_comment = blog_records.comment # preloaded, no SQL fired
like image 76
max pleaner Avatar answered Nov 01 '22 08:11

max pleaner