您应该使用多态关联,以便您将拥有一个评论模型和控制器。根据优秀#154 "Polymorphic Association" Railscast,加入commentable_type:string
和commentable_id:integer
您comments
表后,你的代码应该是这个样子:
# app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
# app/models/judge.rb
class Judge < ActiveRecord::Base
has_many :comments, :as => :commentable
end
# app/models/movie.rb
class Movie < ActiveRecord::Base
has_many :comments, :as => :commentable
end
# app/models/text.rb
class Text < ActiveRecord::Base
has_many :comments, :as => :commentable
end
# app/controllers/comments_controller.rb
def index
@commentable = find_commentable
@comments = @commentable.comments
end
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
if @comment.save
flash[:notice] = "Successfully created comment."
redirect_to :id => nil
else
render :action => 'new'
end
end
private
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
在路线:
# config/routes.rb
map.resources :judges, :has_many => :comments
map.resources :movies, :has_many => :comments
map.resources :texts, :has_many => :comments
,并在视图:
<!-- app/views/comments/index.html.erb -->
<div id="comments">
<% for comment in @comments %>
<div class="comment">
<%=simple_format comment.content %>
</div>
<% end %>
</div>
<h2>New Comment</h2>
<%= form_for [@commentable, Comment.new] do |f| %>
<p>
<%= f.label :content %><br />
<%= f.text_area :content %>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>
如何找到评论所附的原始记录/您如何知道要加入哪张表? – grautur 2010-09-17 20:58:18
我们从未发现您从评论转到评论的项目的情况;我们总是从发票或其他任何东西开始,并问“这附带什么纸条?”如果我需要开始从评论到原始条目,我可能会在注释表中为注释项目的表格添加一列。 – mjfgates 2010-09-18 20:14:22