ruby-on-rails - 从多态模型访问关联
问题描述
我有下一个模型:
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 - 但我不想这样做:(
解决方案
推荐阅读
- java - ServerSocket 在转换为 SSLSocket 时不接受(空指针异常)
- azure-ad-b2c - Azure AD B2C-Graphi api 充电
- maven - Drools kie-ci 示例在 ubber jar 中失败,但在 eclipse IDE 中失败
- c++ - 为什么隐藏符号仍会添加到 DSO
- c - 管道时如何禁用ansi颜色?
- html - 如何在材料自动完成组件中获取对 mat-option 对象的引用
- jenkins - 使用詹金斯管道通过字符串比较在不同参数值之间切换
- php - JSON Post PHP (TypeForm)
- sql - BigQuery 分区表:指定月份的最短方法是什么?
- java - Java 服务:什么导致延迟响应时间尖峰?