Reputation: 305
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
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
Reputation: 3899
Change
@posts = Category.find(params[:id]).posts.mini_posts
to
@posts = Category.find(params[:id]).posts
Upvotes: 1