尝试在帖子中创建评论 - rails

我正在尝试创建一个包含帖子和帖子内评论的社交媒体。 我正在尝试将评论链接到帖子,但进展不顺利。我不知道错误是来自控制器还是视图。这就是我所拥有的:

评论模型:

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

发布模型:

class Post < ApplicationRecord
  belongs_to :user
  has_many :comments
end

路线:

resources :posts do
    member do
      resources :comments
    end
  end

posts 控制器(想法是显示评论表单并显示在帖子内部,并制作一种提要,如 facebook、instagram ..):

class PostsController < ApplicationController

  def index
    @posts = Post.includes(:user).order(updated_at: :desc)
    @comment = Comment.new
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    @post.user = current_user
    if @post.save
      redirect_to request.referrer
      # redirect_to feed_users_path
    else
      render :new
    end
  end

  private

  def post_params
    params.require(:post).permit(:content,:user)
  end
end

评论控制器:

class CommentsController < ApplicationController
  
  def create
    @comment = Comment.new(comment_params)
    @comment.user = current_user
    @comment.post = @post
    if @comment.save
      redirect_to request.referrer
    end
  end

  private

  def comment_params
    params.require(:comment).permit(:content,:post,:user)
  end
end

这是帖子索引:

<% @posts.each do |post| %>
    <div class="row"  id="post-<%= post.id %>">
      <div class="col-12 post-container">

        <!-- header -->
        <div class="post-header d-flex justify-content-start">
          <%= link_to user_path(post.user) do %>
            <h5><%= post.user.first_name  %> <%= post.user.last_name  %></h5>
          <% end %>
          <p>
            <%= link_to user_path(post.user) do %>
              @<%= post.user.first_name %>
            <% end %>
            <span><%= distance_of_time_in_words(Time.now,post.created_at) %></span> ago
          </p>
        </div>

        <!-- content -->
        <div class="post-content">
          <div class="post-text">
            <h4><%= post.content %></h4>
          </div>
        </div>
        <hr>
        <div class="form--input">
          <%= simple_form_for([@post.comment],remote: true) do |f| %>
            <div class="form--input">
              <%= f.input :content,input_html: { class: "form-txt py-3" },placeholder: "What do you want to comment?",label: false %>
            </div>
            <div class="form--input_elements d-flex justify-content-between mx-4">
              <div class="form--input_submit">
                <%= f.submit "Post Comment",class: "btn btn-flat",id: "post-submit",role: "status",remote: true %>
              </div>
            </div>
          <% end %>
        </div>
      </div>
    </div>
<% end %>
xpniree 回答:尝试在帖子中创建评论 - rails

你的路由文件有问题,应该是这样的:

resources :posts do
  resources :comments
end
本文链接:https://www.f2er.com/33495.html

大家都在问