2015-11-09 50 views
1

我想從軌道中的多個表中獲取數據,但它不工作。如何從rails中的多個表關聯中獲取數據?

這是我的代碼。

Category.rb

has_many :posts 

post.rb

has_many :mini_posts 
belongs_to :category 

mini_post.rb

belongs_to :post 

控制器

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

查看文件

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

錯誤顯示「未定義的方法`mini_posts'。

我該如何解決這個問題?

回答

1

變化

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

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

也建議加入.includes(:mini_posts),以改變結束 – Jared

3

您的代碼鏈接的方法,並返回迷你職位,並不急於加載迷你帖子這就是我假設你想要的。

你想要麼

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

或者

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