user3184846
user3184846

Reputation: 3

How to show table from other controller?

I've got two controllers (Users, Posts) with two tables, but I need to pull all the posts from Posts table posted by User.id No matter what I did, I receive NoMethodError in Users#show

user_controller.rb:

class UsersController < ApplicationController 
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  def index 
    @users = User.all 
    @posts = Post.all 
  end
  def show 
    @posts = Post.all 
  end
end

How do you people usually show table from other controller in another controller?

Full error:

NoMethodError in Users#show

Showing ~/users/show.html.haml where line #37 raised:
undefined method `first' for nil:NilClass
Extracted source (around line #37):

34
35 %p
36 %b TEST:
37 = @post.first

Rails.root: ~
Application Trace | Framework Trace | Full Trace

app/views/users/show.html.haml:37:in `_app_views_users_show_html_haml___489713080_88351100'

Upvotes: 0

Views: 109

Answers (2)

wacko
wacko

Reputation: 3424

if you want "all the posts from Posts table posted by User.id', replace @posts = Post.all for @posts = @user.posts on #show method

Upvotes: 0

gotva
gotva

Reputation: 5998

@post.first this code raises the exception. You defined @posts not @post!

Upvotes: 3

Related Questions