I have a rails application where I generated some scaffold for a title (string) and body (content) for ‘posts’.
This allows me to create, edit and delete a post.
I’ve just installed devise so now I can have users in the application – the only problem is that no matter what I’m logged in as, the same posts show up.
Is there a way to have specific posts to each user? Would I have to change the post or user model or add a new controller?
If that confused you, another way to put it is that I’d like for each user to create their own ‘posts’ that other users can’t see.
Update
Here is the posts_controller
class PostsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
# GET /posts
# GET /posts.json
def index
# @posts = current_user.posts
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
# GET /posts/1
# GET /posts/1.json
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
# GET /posts/new
# GET /posts/new.json
def new
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @post }
end
end
# GET /posts/1/edit
def edit
@post = Post.find(params[:id])
end
# POST /posts
# POST /posts.json
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render json: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# PUT /posts/1
# PUT /posts/1.json
def update
@post = Post.find(params[:id])
respond_to do |format|
if @post.update_attributes(params[:post])
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
@post = Post.find(params[:id])
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
end
And here is the post model
class Post < ActiveRecord::Base
attr_accessible :content, :name
belongs_to :user
end
In your Posts controller use
@posts = current_user.postsin the index method.You will need to have the Post
belongs_toUser / Userhas_manyposts relationships set up in the Post and User models.Now your view for posts/index can iterate over @posts and they’ll just be for that user.