【发布时间】:2016-01-27 12:14:47
【问题描述】:
我的 Rails 应用程序中有几个模型,它们是:
- 用户
- 照片
- 专辑
- 评论
我需要让 cmets 隶属于 Photo 或 Album,并且显然始终属于 User。我将为此使用polymorphic associations。
# models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, :polymorphic => true
end
问题是,Rails 描述新评论的#create 动作的方式是什么。我看到了两种选择。
1.描述每个控制器中的评论创建
但这不是一个 DRY 解决方案。我可以制作一个通用的局部视图来显示和创建 cmets,但我将不得不重复自己为每个控制器编写 cmets 逻辑。所以它不起作用
2。创建新的 CommentsController
我猜这是正确的方式,但据我所知:
要完成这项工作,您需要同时声明一个外键列和一个 模型中声明多态接口的类型列
像这样:
# schema.rb
create_table "comments", force: :cascade do |t|
t.text "body"
t.integer "user_id"
t.integer "commentable_id"
t.string "commentable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
所以,当我将编写非常简单的控制器时,它将接受来自远程表单的请求:
# controllers/comments_controller.rb
class CommentsController < ApplicationController
def new
@comment = Comment.new
end
def create
@commentable = ??? # How do I get commentable id and type?
if @comment.save(comment_params)
respond_to do |format|
format.js {render js: nil, status: :ok}
end
end
end
private
def comment_params
defaults = {:user_id => current_user.id,
:commentable_id => @commentable.id,
:commentable_type => @commentable.type}
params.require(:comment).permit(:body, :user_id, :commentable_id,
:commentable_type).merge(defaults)
end
end
如何获得commentable_id 和commetable_type?我猜,commentable_type 可能是型号名称。
另外,从其他视图制作form_for @comment 的最佳方法是什么?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 activerecord polymorphic-associations