Question

I have a blog that use devise for authentication and where user can create posts, I have created a basic dashboard where users will be able to manage their posts

this is my dashboard controller

before_action :authenticate_user!
def index
 @posts = Post.find(:all, :conditions => [ "user_id = ?", @current_user ]) 
end

this my dashboard view

<% @posts.each do |post| %> 
 <%= post.content %> 
<% end %> 

this my user model

has_many :posts

and my post model

belongs_to :user

this is my schema.rb

  create_table "posts", force: true do |t|
    t.text     "content"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

but when i go to the dashboard i am not getting any of my post and when i change my dashboard controller to

def index
 @posts = Post.all
end

I'am getting all the posts so can someone tell me where is my fault

Was it helpful?

Solution

The find(:all, :conditions => []) was deprecated in Rails 3.2. Instead try:

def index
  @posts = Post.where(:user_id => current_user)
end

Also, make sure you are adding a user_id in the create method in your controller:

def create
  @post = post.new(post_params)
  @post.user_id = current_user

  REST OF CODE GOES HERE
end

OTHER TIPS

Replace

@posts = Post.find(:all, :conditions => [ "user_id = ?", @current_user ])

with

@posts = @current_user.posts

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top