【问题标题】:Rails polymorphic comments undefined method user_nameRails 多态注释未定义方法 user_name
【发布时间】:2013-11-13 06:14:41
【问题描述】:

所以我遵循 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

评论控制器:

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

媒体控制器:

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

任何人都知道为什么会发生这种情况,因为我被卡住了。谢谢。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      相关资源
      最近更新 更多