Я новичок в рельсах и пытаюсь создать страницу блога типа Reddit.В настоящее время я работаю над вложенными комментариями, чтобы пользователь мог отвечать на комментарии.В моем приложении есть форумы, посты и комментарии.Создание сообщений и форумов работало отлично, также я оставлял комментарии, пока я не попытался вложить ответы.Мой код выглядит следующим образом (модели и контроллеры для пользователей и форумов опущены):
Модель моего комментария:
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
belongs_to :user
has_many :comments, as: :commentable
end`
Модель моего сообщения:
class Post < ApplicationRecord
belongs_to :forum
belongs_to :user
has_many :comments, as: :commentable, dependent: :destroy
end
Мойposts_controller:
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = find_post
end
def new
@post = Post.new
end
def edit
@post = find_post
end
def create
@forum = Forum.find(params[:forum_id])
@post = @forum.posts.create(post_params.merge(user_id: current_user.id))
redirect_to forum_path(@forum)
end
def update
@post = find_post
if @post.update(post_params)
redirect_to forum_path
else
render 'show'
end
end
def destroy
@post = find_post
@post.destroy
redirect_to forum_path
end
private
def post_params
params.require(:post).permit(:title, :content)
end
private
def find_post
@forum = Forum.find(params[:forum_id])
@forum.posts.find(params[:id])
end
end
Мои комментарии_контроллер:
class CommentsController < ApplicationController
before_action :find_commentable
def index
@comments = Comment.all
end
def new
@comment = Comment.new
end
def create
@comment = @commentable.comments.create(comment_params.merge(user_id: current_user.id))
if @comment.save
@post = Post.find_by_id(params[:post_id])
redirect_to forum_post_path(@post.forum_id, @post), notice: 'Your comment was successfully posted!'
else
redirect_to forum_post_path(@post.forum_id, @post), notice: 'error :('
end
end
private
def comment_params
params.require(:comment).permit(:content)
end
private
def find_commentable
@commentable = Comment.find_by_id(params[:comment_id]) if params[:comment_id]
@commentable = Post.find_by_id(params[:post_id]) if params[:post_id]
end
end
Мои просмотры / комментарии / _комментарий:
<li>
<%= comment.content %>
<small>Submitted <%= time_ago_in_words(comment.created_at) %> ago</small>
<h2>Add a Reply:</h2>
<%= form_with(model: [ comment, comment.comments.build ], local: true) do |form| %>
<p>
<%= form.text_area :content, placeholder: "Add a Reply" %><br/>
<%= form.submit %>
</p>
<% end %>
<ul>
<%= render partial: 'comments/comment', collection: comment.comments if comment.comments.any? %>
</ul>
<%= link_to 'Back', forum_post_path(@forum, @post) %>
Мои просмотры / публикация / шоу:
<small>Submitted <%= time_ago_in_words(@post.created_at) %> ago</small>
<h3>Comments</h3>
<ul>
<%= render(partial: 'comments/comment', collection: @post.comments) if @post.comments.any?%>
</ul>
<h2>Add a comment:</h2>
<%= form_with(model: [ @post, @post.comments.build ], local: true) do |form| %>
<%= form.text_field :content, placeholder: "Add a comment" %><br/>
<%= form.submit "Add Comment" %>
<% end %>
<%= link_to 'Back', forum_path(@forum) %>
<%= link_to 'All posts', forum_posts_path(@post.forum_id) %>
<%= link_to 'All comments', post_comments_path(@post) %>
</li>
Мои маршруты:
resources :posts do
resources :comments
end
resources :comments do
resources :comments
end
Первые ошибки, которые я продолжал получать, заключались в том, что каждый раз, когда я отправлял комментарий в view/posts/show
, этот комментарий не создавался.Теперь views / comments / _comment выводит сообщение об ошибке:
Showing /example/app/views/comments/_comment.html.erb where line #3 raised:
nil can't be converted to a Time value
<small>Submitted <%= time_ago_in_words(comment.created_at) %> ago</small>
после отправки нового комментария.Любая помощь в отношении этой ошибки ценится или связана с моей главной целью, я уже давно обхожусь вокруг этого.Спасибо!