Rails多态注释未定义方法user_name

时间:2013-11-01 23:25:03

标签: ruby-on-rails comments polymorphic-associations

所以我跟着Railscast 154关于实现多态关联,我能够启动并运行,但每当我尝试调用评论的用户时,我得到一个未定义的方法。

这是我的迁移:

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.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 %>

任何人都知道为什么会这样,因为我被困住了。感谢。

1 个答案:

答案 0 :(得分:2)

好吧,我解决了自己的问题。问题是没有成员与评论相关联。我必须在comments_controller中修改创建操作:

def create
    @comment = @commentable.comments.new(params[:comment])
    @comment.member = current_member
    if @comment.save
      redirect_to :back
    else
      render :new
    end
end