ruby-on-rails - 多态关联中的注释重构Form_for Create方法

标签 ruby-on-rails ruby-on-rails-3 polymorphic-associations

我正在处理我的第一个多态关联关系,但在重构我的 form_for 创建评论时遇到了麻烦。

我尝试通过多态关联 RailsCasts http://railscasts.com/episodes/154-polymorphic-association?view=asciicast ,但似乎过时了。

我有两个问题:

  • 我如何重写我的 comment_form 部分,以便它适用于任何可评论的内容?我现在拥有它的方式,它只适用于自 (:commentable_id => @traveldeal.id) 以来的 traveldeals .
  • 当我创建评论时,commentable_type 为空。什么是 commentable_type,我需要在表单中传递它吗?

  • 谢谢!

    用户名
    class User < ActiveRecord::Base
      has_many :comments, :dependent => :destroy
    end
    

    traveldeal.rb
    class Traveldeal < ActiveRecord::Base
      has_many :comments, :as => :commentable, :dependent => :destroy
    end
    

    评论.rb
    class Comment < ActiveRecord::Base
      belongs_to :user
      belongs_to :commentable, :polymorphic => true
    
      validates :user_id, :presence => true
      validates :commentable_id, :presence => true
      validates :content, :presence => true
    end
    

    traveldeal_show.html.erb
    <%= render 'shared/comment_form'  %>
    

    _comment_form.html.erb
    <%= form_for current_user.comments.build(:commentable_id => @traveldeal.id) do |f| %>
      <%= render 'shared/error_messages', :object => f.object %>
    
    <div>
      <%= f.text_area :content %>
    </div>
    
    <%= f.hidden_field :user_id %>
    <%= f.hidden_field :commentable_id %>
    
    <div>
      <%= f.submit "Add Comment" %>
    </div>
    <% end %>
    

    评论 Controller .rb
    class CommentsController < ApplicationController
      before_filter :authenticate, :only => [:create, :destroy]
    
      def create
        @comment = Comment.new(params[:comment])
        @comment.save
        redirect_to root_path
      end
    
    end
    

    最佳答案

    Railscast 中唯一注明日期的部分是路线。

    回答你的第一个问题:像在 Railscast 中一样创建你的表单:

    <%= form_for [@commentable, Comment.new] do |f| %>
      <p>
        <%= f.label :content %><br />
        <%= f.text_area :content %>
      </p>
      <p><%= f.submit "Submit" %></p>
    <% end %>
    

    如果你这样做 commentable_type会自动设置。您需要类型,以便您知道评论属于哪个模型。请注意,您必须设置 @commentable在您使用评论表单的方法中。

    例如。
    class TraveldealsController < ApplicationController
      def show
        @traveldeal = @commentable = Traveldeal.find(params[:id])
      end
    end
    

    关于ruby-on-rails - 多态关联中的注释重构Form_for Create方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10113981/

    相关文章:

    ruby-on-rails - Rails 3 gmaps4rails(点击 map )

    ruby-on-rails - Bootstrap-Sass 不适用于 Rails 4

    ruby-on-rails - 如何在AJAX中优雅地处理devise的401状态?

    ruby-on-rails - 安装 rails ActiveAdmin 引擎位于可安装引擎内

    jquery - Rails 3 使用链接呈现不同的部分

    ruby-on-rails - 如何更改现有的评论模型,使其可以属于许多不同的模型?

    ruby-on-rails - 使用 RSpec 测试多态关联

    ruby-on-rails - 如何将收到的短信(通过 twilio)与我的 Rails 应用程序中的特定用户关联

    facebook - 使用 fb_graph gem 删除 Facebook feed 帖子

    php - PropelORM和数据库结构