首页 > 解决方案 > 从多态模型访问关联

问题描述

我有下一个模型:

class Post < ActiveRecord::Base
    has_many :comments, as: :commentable
end

class Article < ActiveRecord::Base
    has_many :comments, as: :commentable
end

class Comment < ActiveRecord::Base
    belongs_to :commentable, polymorphic: true
end

现在我可以通过 获取帖子和文章@comment.commentable,但我需要通过@comment.post@comment.article。我找到了一些解决方案,但它不适用于嵌套属性:

accepts_nested_attributes_for :article
accepts_nested_attributes_for :post

我的comments_controller

class CommentsController < ApplicationController
  def create
    @comment = Comment.new(comment_params)

    if @comment.save!
      head :ok, location: @comment
    else
      render json: @comment.errors, status: :unprocessable_entity
    end
  end

  private

  def comment_params
    params.require(:comment).permit(
      :text, text: {},
      post_attributes: [:id, text: {}],
      article_attributes: [:id, text: {}]
    )
  end
end

从表单中发布参数,例如:

    const params = {
      comment: {
        text,
        post_attributes: [{
          id: post ? post.id : null,
          text,
        }]
      }
    }

如果帖子或文章不存在,则必须创建它。或者像这里一样添加一个模型https://gist.github.com/runemadsen/1242485 - 但我不想这样做:(

标签: ruby-on-railsactiverecord

解决方案


推荐阅读