Rails多态注释未定义方法user_name

所以我跟着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_controller中修改我的创建操作:

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