Rails два вложенных атрибута, "комментарии" к "сообщениям" и к "проблемам", не сохраняющим откат - PullRequest
1 голос
/ 25 мая 2019

Это код контроллера, который не удается сохранить.

     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 голосов
/ 25 мая 2019

Проблема в том, что вам не хватает связанных post и user.Вам нужно будет либо убедиться, что оба существуют, и передать действительные post_id и user_id, либо сделать:

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

В настоящее время вы объединяетесьидентификатор 0 для обоих, который никогда не может принадлежать действительной записи любого типа.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...