跟踪两个嵌套属性,即“帖子”和“问题”上的“注释”,不保存回滚

时间:2019-05-25 00:09:01

标签: nested ruby-on-rails-5 rollback

这是无法保存的控制器代码。

     def create
        if params[:post_id]
            @post = Post.find(params[:post_id])
            @comment = @post.comments.new(comment_params)
        elsif params[:issue_id]
            @issue = Issue.find(params[:issue_id])
            @comment = @issue.comments.new(comment_params)
        end
        if @comment.save
            if @comment.issue_id
                redirect_to Issue.find(@comment.issue_id)
            elsif @comment.post_id
                redirect_to Post.find(@comment.post_id)
            end
        else
            redirect_to edit_username_path(current_user)
        end
    end
    ...
    def comment_params
        params.require(:comment).permit(:content)
    end

然后是评论表:

      <%= simple_form_for [@issue, @issue.comments.build] do |f| %>
        <%= csrf_meta_tags %>
        <%= f.input :content, required: true, input_html: { class: 'textarea', id: 'issuecommentnew' } %>
        <%= f.button :submit, "Create New Comment" %>
      <% end %>

如果我四处移动,我可以将其重定向回问题,但不会保存任何评论。

这是参数输出:

{"utf8"=>"✓", "authenticity_token"=>"gNiPWM8IMa25LC0qKZ1WPnGbW4rnRCXXZficHoSM/b+t4jdcNVPS3xn4/PGjam/QiJPdMjluilIw32E2KafXJQ==", "comment"=><ActionController::Parameters {"content"=>"hello"} permitted: false>, "commit"=>"Create New Comment", "controller"=>"comments", "action"=>"create", "issue_id"=>"1"}

注释模型:

class Comment < ApplicationRecord
    belongs_to :post
    belongs_to :user
    belongs_to :issue

    after_commit :create_notifications, on: :create

    private

    def create_notifications
        Notification.create do |notification|
            notification.notify_type = "post"
            notification.actor = self.user
            notification.user = self.post.user
            notification.target = self
            notification.second_target = self.post
        end
    end

end

在架构中:

create_table "comments", force: :cascade do |t|
    t.text "content"
    t.integer "post_id"
    t.string "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "issue_id"
  end

我包括了:

comment_params.merge(user: current_user, post: 0)issue: 0

还有

ActiveRecord::RecordInvalid - Validation failed: Post must exist, User must exist:

ActiveRecord::AssociationTypeMismatch - Post(#70348245809340) expected, got 0 which is an instance of

已解决:

issue: Issue.new

1 个答案:

答案 0 :(得分:0)

问题是您缺少关联的postuser。您必须确保两者都存在,并传递有效的post_iduser_id,或者执行以下操作:

belongs_to :post, optional: true belongs_to :user, optional: true

您当前正在为这两者合并一个ID,该ID永远不会属于这两种类型的有效记录。