0
I’m trying to display user posts on perfil = link_to 'perfil', user_path(user)
User data appears, but when I try to show user posts comes error:
Nomethoderror in Userscontroller#show Undefined method 'posts' for #<
Class:0x007f4c48fdbb50>
The code shown with error
users_controller
def show
@user = User.find(params[:id])
@posts = User.posts #aqui a linha marcada
end
posts.controller
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@posts = Post.all
respond_with(@posts)
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
respond_with(@post)
end
def edit
end
def create
@post = Post.new(post_params)
@post.save
respond_with(@post)
end
def update
@post.update(post_params)
respond_with(@post)
end
def destroy
@post.destroy
respond_with(@post)
end
private
def set_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :content)
end
end
model/posts.Rb
class Post < ActiveRecord::Base
include PublicActivity::Model
tracked owner: ->(controller, model) { controller && controller.current_user }
has_many :coments
belongs_to :user
validates :content, presence: true, length: { maximum: 200 }
end
model/user.Rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
has_many :coments
has_many :posts, dependent: :destroy
has_many :friendships
has_many :friends, through: :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
has_many :messages, dependent: :destroy
has_many :properties, dependent: :destroy
has_many :partnerships
belongs_to :city
has_one :state, through: :city
has_one :profile
mount_uploader :avatar, ImageUploader
validates :terms, acceptance: { message: "Você precisa aceitar os termos de uso" }
validates :name, :city_id, presence: true
def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
if user
user
else
registered_user = User.where(:email => auth.info.email).first
if registered_user
registered_user
else
user = User.create(
name: auth.extra.raw_info.name,
provider: auth.provider,
uid: auth.uid,
email: auth.info.email,
password: Devise.friendly_token[0,20],
remote_avatar_url: auth.info.image.gsub('http://','https://').gsub('picture', 'picture?type=large')
)
end
end
end
end
I believe the problem lies in your model of
User
. In it existshas_many :posts
? Click [Edit] and place this other Model please.– gmsantos
@gmsantos put the model, and has has_many :posts The same error also happens when having '@properties = User properties.'
– Curt Bercht Neto