问题
I am working on my first polymorphic association relationship and I am having trouble refactoring my form_for create comments.
I tried going through the Polymorphic Association RailsCasts http://railscasts.com/episodes/154-polymorphic-association?view=asciicast, but it seems dated.
I have two questions:
How do I rewrite my comment_form partial so that it would work for anything commentable? The way I have it right now, it would only work for traveldeals since
(:commentable_id => @traveldeal.id)
.When I create the comment, the commentable_type is empty. What is commentable_type and do I need to pass it in the form?
Thanks!
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
comment.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 %>
comments_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
回答1:
The only part that is dated in the Railscast are the routes.
To answer your first question: create your form like it is done in the Railscast:
<%= form_for [@commentable, Comment.new] do |f| %>
<p>
<%= f.label :content %><br />
<%= f.text_area :content %>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>
If you do it like this commentable_type
will be set automatically. You need the type so you know to what model a comment belongs. Note that you have to set @commentable
in the method where you use the comment form.
E.g.
class TraveldealsController < ApplicationController
def show
@traveldeal = @commentable = Traveldeal.find(params[:id])
end
end
来源:https://stackoverflow.com/questions/10113981/refactoring-form-for-create-method-for-comments-in-a-polymorphic-association