多态form_for

时间:2012-07-24 19:42:42

标签: ruby-on-rails-3

我正在尝试在页面上创建添加评论表单,但它需要在同一页面上多次出现。

这是我的模特。我正在使用Mongoid 3.0,但我认为不重要。模型工作正常。

class Project
  include Mongoid::Document
  ...
  embeds_many :comments, :as => :commentable
  ...
end

class Suggestion
  include Mongoid::Document
  ...
  embeds_many :comments, :as => :commentable
  ...
end

class Comment
  include Mongoid::Document
  embedded_in :commentable, :polymorphic => true
  ...
end

我有这些路线

suggestion_comments POST   /suggestions/:suggestion_id/comments(.:format) comments#create
project_comments POST   /projects/:project_id/comments(.:format)       comments#create

我通过以下方式致电表格:

= render partial: "comments/new", locals: { :commentable => stream.project }
= render partial: "comments/new", locals: { :commentable => stream.suggestion }

如何创建form_for?我试过这个,但它不起作用。此外,由于我需要多次在页面上显示此内容,因此在页面上复制的CSS id将导致此页面上的JavaScript出现问题。

= form_for commentable.comments, remote: true do |f|
  %fieldset
    .control-group
      .controls
        = f.text_area :content, :required => true, :placeholder => "Add a comment...", :maxlength => "1000"
    .form-actions
      = f.submit "Post"

1 个答案:

答案 0 :(得分:0)

经过大量的尝试,我终于想通了......结果很简单:

= simple_form_for([commentable, Comment.new], :remote => true) do |f|