Как сделать комментарии к сообщениям доступными на моей домашней странице и в представлении пользователя / шоу?

Вот мой домашний контроллер:

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? Мне удалось получить доступ и просмотреть сообщения в домашнем просмотре и # шоу пользователя, но у меня возникли проблемы с доступом к комментариям.

1 ответ

Решение

Самый простой способ.

UserController # индекс

@posts = current_user.posts

в шоу HTML

render @posts

Для правильной визуализации постов у вас должен быть _post.html.erb, чтобы rails знал, как их визуализировать.

Другие вопросы по тегам