这是我的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
这是我的评论控制器:
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
我的帖子控制器:
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
我的用户模型:
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
我的帖子模型:
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
如何确保可以在主页(对应于主视图的homeController)和用户#show中访问帖子及其评论?我能够访问和查看homeview中的帖子和用户#show,但我无法访问评论。
答案 0 :(得分:0)
最简单的方法。
UserController的#索引
@posts = current_user.posts
在show html中
render @posts
为了正确呈现帖子,你必须有一个_post.html.erb,以便rails知道如何呈现它们。