acts_as_commentable
パウロが提案したように、またはpolymorphic-association
http://asciicasts.com/episodes/154-polymorphic-association
または railscasts の PRO アカウント: http://railscasts.com/episodes/154-polymorphic-association-revised (リポジトリ: https://github.com/railscasts/154-polymorphic-association-revised/tree/master/blog -後)
以下の少し変更されたコードでは、このコードを使用すると、Post
でロード@commentable
したときにのみ にコメント@commentable = Post.find(params[:id])
を追加できます。チュートリアルを進めると、User と Post が同じ Comment モデルを共有するアプリ内の他のモデルにコメントを追加できるようになります。 .
acts_as_commentable
以前はアプリで使用していた素敵な宝石ですが、polymorphic-association
今ははるかにカスタマイズ可能であるため、使用しています。
post.rb
attr_accessible :content, :name
has_many :comments, as: :commentable
コメント.rb
attr_accessible :content
belongs_to :commentable, polymorphic: true
show.html.erb
<h1>Comments</h1>
<ul id="comments">
<% @comments.each do |comment| %>
<li><%= comment.content %></li>
<% end %>
</ul>
<h2>New Comment</h2>
<%= form_for [@commentable, @comment] do |f| %>
<ol class="formList">
<li>
<%= f.label :content %>
<%= f.text_area :content, :rows => 5 %>
</li>
<li><%= f.submit "Add comment" %></li>
</ol>
<% end %>
投稿コントローラー
def show
@post = Post.find(params[:id])
@commentable = @post
@comments = @commentable.comments
@comment = Comment.new
end
コメント_コントローラー
def create
@commentable = Post.find(params[:id])
@comment = @commentable.comments.new(params[:comment])
if @comment.save
redirect_to @commentable, notice: "Comment created."
else
render :new
end
end
ルート.rb
resources :posts do
resources :comments
end