私は最初のポリモーフィック アソシエーション関係に取り組んでおり、form_for create コメントのリファクタリングに問題があります。
Polymorphic Association RailsCasts http://railscasts.com/episodes/154-polymorphic-association?view=asciicastを調べてみましたが、時代遅れのようです。
2 つの質問があります。
コメント可能なものに対して機能するように、comment_form パーシャルを書き直すにはどうすればよいですか? 私が今持っている方法では、
(:commentable_id => @traveldeal.id)
.コメントを作成すると、commentable_type が空になります。commentable_type とは何ですか?フォームで渡す必要がありますか?
ありがとう!
user.rb
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 %>
コメント_コントローラー.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