Here is my homeController:
class HomeController < ApplicationController
def home
if logged_in?
@post = current_user.posts.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
def about
end
def privacy
end
def terms
end
end
Here is my Comments Controller:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
redirect_to root_path
end
private
def comment_params
params.require(:comment).permit(:author_name, :body)
end
end
My posts controller:
class PostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = "Post created!"
redirect_to root_url
else
@feed_items = []
render 'home/home'
end
end
def destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:title, :body, :picture)
end
end
My user model :
class User < ActiveRecord::Base
attr_accessor :remember_token
before_save { self.email = email.downcase }
has_many :posts, dependent: :destroy
has_many :comments
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
.............................................
.............................................
end
My post model:
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
default_scope -> { order(created_at: :desc) }
mount_uploader :picture, PictureUploader
validates :user_id, presence: true
validates :body, presence: true, length: { minimum:40 }
end
How do I make sure both the posts and their comments can be accessed in the home page( homeController corresponding to the home view) and the user#show ? I was able to access and view the posts in homeview and the user#show but I am having trouble with accessing the comments.
Easiest way.
UserController#index
@posts = current_user.posts
in show html
render @posts
In order to render the posts correctly you will have to have a _post.html.erb so that rails knows how to render them.