Rails 4 - 多态关联 - 嵌套属性

时间:2016-01-02 01:31:32

标签: ruby-on-rails simple-form polymorphic-associations

我正在尝试使用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

文章/ 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"

2 个答案:

答案 0 :(得分:0)

尝试:

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

答案 1 :(得分:0)

很多问题。

这应该是它的样子:

-

destroy()

您应该将注释创建为自己的实体(而不是文章的嵌套属性)。您应该使用以下内容执行此操作:

#config/routes.rb
resources :articles do
  get :search, on: :collection
  resources :comments, module: :articles #-> url.com/articles/:article_id/comments
end

#app/controllers/articles/comments_controller.rb #-> this is the heroku error
class Articles::CommentsController < ApplicationController
    before_action :set_article
    respond_to :js, :json, :html

    def create
       @comment = @article.comments.new comment_params
       respond_with @comment
    end

    private

    # Use callbacks to share common setup or constraints between actions.
    def set_article
       @article = Article.find params[:article_id]
    end

    def comment_params
       params.require(:comment).permit(:opinion).merge(user: current_user)
    end
end

这应该会在#app/views/articles/show.html.erb <%= content_tag :div, render(partial: 'comments/form', locals: { article: @article }), class: "col-xs-12" %> #app/views/comments/_form.html.erb <%= simple_form_for [article, article.comments.new] do |f| %> <%= f.input :opinion, as: :text, label: "Add your thoughts", input_html: {rows: 4} %> <%= f.submit %> <% end %> 的背面创建一个独立的评论。