So I followed the Railscast 154 about implementing polymorphic associations and I was able to get it up and running, but whenever I try to call the user who commented I get an undefined method.
Here's my Migration:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.belongs_to :commentable, polymorphic: true
t.references :member
t.timestamps
end
add_index :comments, [:commentable_id, :commentable_type]
add_index :comments, :member_id
end
end
CommentsController:
class CommentsController < ApplicationController
before_filter :authenticate_member!
before_filter :load_commentable
def create
@comment = @commentable.comments.new(params[:comment])
if @comment.save
redirect_to :back
else
render :new
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
if @comment.destroy
redirect_to :back
end
end
private
def load_commentable
klass = [Status, Medium].detect { |c| params["#{c.name.underscore}_id"] }
@commentable = klass.find(params["#{klass.name.underscore}_id"])
end
MediaController:
def show
@medium = Medium.find(params[:id])
@commentable = @medium
@comments = @commentable.comments
@comment = Comment.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: @medium }
end
end
Comments Form:
<% @comments.each do |comment| %>
<div class="comments">
<span class="content">
<%= comment.member.user_name %>
<%= comment.content %>
</span>
<span class="comment_del">
<%= link_to image_tag("delete-6-icon.png"), [@commentable, comment], method: :delete, data: { confirm: 'Are you sure?' } %>
</span>
</div>
<% end %>
Anyone know why this might be happening because I'm stuck. Thanks.