我正在尝试使用Rails 4制作一个应用程序。
我对表格使用简单的表格。
我正在尝试遵循本教程,以便可以使用我的多态注释模型为文章添加注释。https://gorails.com/episodes/comments-with-polymorphic-associations?autoplay=1
我有以下文章和评论模型:
article.rb
has_many :comments, as: :commentable
accepts_nested_attributes_for :comments
comment.rb
belongs_to :user
belongs_to :commentable, :polymorphic => true
如视频教程所示,已经设置了注释控制器:
comments_controller.rb
article / comments_controller.rb
文章控制器具有:
def new
@article = Article.new
@article.comments.build
end
def article_params
params[:article].permit(:user_id, :body, :title, :image, :tag_list,
comment_attributes: [:opinion])
end
文章显示页面具有:
<div class="col-xs-12">
<%= render :partial => 'comments/form', locals: {commentable: @article} %>
</div>
评论表单的部分内容包括:
<%= simple_form_for [commentable, Comment.new] do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :opinion, as: :text, :label => "Add your thoughts", :input_html => {:rows => 4} %>
</div>
<div class="form-actions">
<%= f.button :submit, "Submit", :class => 'formsubmit' %>
</div>
<% end %>
路线是:
resources :articles do
collection do
get 'search'
end
resources :comments, module: :articles
end
当我保存所有这些并尝试呈现文章显示页面时,出现此错误:
#的未定义方法“ new”
该错误指向注释控制器创建动作:
def create
@comment = @commentable.new(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to @commentable }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
我不知道问题是什么。我不明白为什么这不起作用或此错误消息的含义。我想知道是否因为评论同时属于用户和可评论。
实际上,当我按此按钮并尝试在生产模式下查看它时,我失败了,并且heroku日志显示此错误:
Exiting
2016-01-02T02:27:59.274318+00:00 app[web.1]: /app/app/controllers/Articles/comments_controller.rb:1:in `<top (required)>': uninitialized constant Articles (NameError)
整个文章/评论控制器具有:
class Articles::CommentsController < CommentsController
before_action :set_commentable#, only: [:show, :edit, :update, :destroy]
private
# Use callbacks to share common setup or constraints between actions.
def set_commentable
@commentable = Article.find(params[:article_id])
end
end
因此,这现在适用于新文章,但仅适用于1条评论。如果尝试在单篇文章中添加第二条评论,则会出现此错误:
PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_comments_on_commentable_type_and_commentable_id" DETAIL: Key (commentable_type, commentable_id)=(Article, 4) already exists. : INSERT INTO "comments" ("opinion", "user_id", "commentable_id", "commentable_type", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"
尝试:
def create
@comment = Comment.new(comment_params)
@comment.user = current_user
@comment.commentable = @commentable
respond_to do |format|
if @comment.save
format.html { redirect_to @comment }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句