vanhiro
vanhiro

Reputation: 305

How can I get data from multiple table association in rails?

I want to get data from multiple table in rails,but it is not working.

Here is my code.

Category.rb

has_many :posts

post.rb

has_many :mini_posts
belongs_to :category

mini_post.rb

belongs_to :post

controller

@posts = Category.find(params[:id]).posts.mini_posts

viewfile

<% @posts.each do |post| %>
    <%= post.title %>
    <%= post.description %>
  <% post.mini_posts.each do |mpost| %>
    <%= mpost.name %>
    <%= mpost.experience %>
  <% end %>
<% end %>

The error shows "undefined method `mini_posts'.

How can I solve this?

Upvotes: 1

Views: 37

Answers (2)

j-dexx
j-dexx

Reputation: 10406

Your code is chaining methods, and returning mini posts, not eager loading the mini posts which is what I assume you want.

You want either

@posts = Post.includes(:mini_posts).where(category_id: params[:id])

Or

@category = Category.includes(posts: :mini_posts).find(params[:id])
@posts = @category.posts

Upvotes: 3

John Pollard
John Pollard

Reputation: 3899

Change

@posts = Category.find(params[:id]).posts.mini_posts

to

@posts = Category.find(params[:id]).posts

Upvotes: 1

Related Questions