Ancestry
我打算给你一个关于如何分配的想法parent_id
根据您的需要,但考虑到我们已经创建了评论系统之前我觉得给大家一些系统性的想法比较好;而不是具体细节
我们使用一种名为Ancestry使我们能够嵌套对象:
这使我们能够灵活地创建更强大的嵌套结构(我将稍后详细介绍):
#config/routes.rb
resources :posts do
resources :comments, only: [:new, :create] do
get :reply #-> domain.com/posts/:post_id/comments/:id/reply
end
end
#app/controllers/comments_controller.rb
Class CommentsController < ApplicationController
def new
@post = Post.find params[:post_id]
@comment = Comment.new
end
def reply
@post = Post.find params[:post_id]
@comment = Comment.new
@parent = params[:id]
render :new
end
def create
@post = Post.find params[:post_id]
@comment = @post.comments.new comment_params
@comment.save
end
private
def comment_params
params.require(:comment).permit(:body, :ancestry)
end
end
#app/views/comments/new.html.erb
<%= form_for [@post, @comment] do |f| %>
<%= f.text_field :body %>
<%= f.hidden_field :ancestry, value: @parent if @parent.present? %>
<%= f.submit %>
<% end %>
使用之美ancestry
(我推荐的真正原因)是能够创建真正的嵌套视图:
为此,您可以使用我们创建的部分:
#app/comments/index.html.erb
<%= render partial: "category", collection: @comments, as: :collection %>
#app/comments/_comment.html.erb
<% collection.arrange.each do |comment, sub_item| %>
<li>
<%= link_to comment.title, comment_path(comment) %>
<% if comment.has_children? %>
<%= render partial: "comment", locals: { collection: comment.children } %>
<% end %>
</li>
<% end %>
--
Dropdown
#app/helpers/application_helper.rb
def nested_dropdown(items)
result = []
items.map do |item, sub_items|
result << [('- ' * item.depth) + item.name, item.id]
result += nested_dropdown(sub_items) unless sub_items.blank?
end
result
end
#app/views/posts/new.html.erb
<%= form_for @post do |f| %>
<%= f.select(:category_ids, nested_dropdown(Category.all.arrange), prompt: "Category", selected: @category ) %>
<% end %>