ruby on rails - How do I make the Posts comments available in my homepage and user/show view? -
here 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 end def privacy end def terms end end
here 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 share common setup or constraints between actions. def set_post @post = post.find(params[:id]) end # never trust parameters scary internet, allow 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 make sure both posts , comments can accessed in home page( homecontroller corresponding home view) , user#show ? able access , view posts in homeview , user#show having trouble accessing comments.
easiest way.
usercontroller#index
@posts = current_user.posts
in show html
render @posts
in order render posts correctly have have _post.html.erb rails knows how render them.
Comments
Post a Comment