uninitialized constant Like :: Likeable错误与多态关联rails

时间:2015-07-15 20:51:13

标签: ruby-on-rails ruby ruby-on-rails-4

尝试在我的应用中创建多态关联的实例时出现此错误。我的想法是,我可以添加喜欢Microposts和Images模型。出于某种原因,我不断收到此错误 LikesController中的NameError #create 未初始化的常数Like :: Likeable

模型

 class Like < ActiveRecord::Base

   belongs_to :user
   belongs_to :likeable, polymorphic: true

   validates :likeable, presence: true, uniqueness: { scope: :likeable_id }
   validates :user, presence: true, uniqueness: { :scope => [:likeable_id, :likeable_type] }
 end

 class User < ActiveRecord::Base
   has_many :likes, dependent: :destroy
 end

 class Micropost < ActiveRecord::Base
   has_many :likes, as: :likeable, dependent: :destroy
 end

控制器

class LikesController < ApplicationController

  before_filter :find_likeable
  before_action :logged_in_user

  # Like a model
  def create
    @user = current_user
    @like = @user.likes.build(likeable: @likeable)
    @like.save

    respond_to do |format|
      format.html { redirect_to root_url }
      format.js
    end
  end

  # Dislike a model
  def destroy
    @user = current_user
    @like = @user.likes.find_by_likeable_id(params[:likeable_id])
    @like.destroy

    respond_to do |format|
      format.html { redirect_to root_url }
      format.js
    end
  end

  private
    def find_likeable  
      resource, id = request.path.split("/")[1,2]
      @likeable = resource.singularize.classify.constantize.find(id)
    end
end

路线

resources :microposts, only: [:create, :destroy] do
  resources :comments, only: [:create, :destroy]
  resources :likes, only: [:create, :destroy]
end

Partial _button_like.html.erb

<% if current_user.like?(likeable) %>
<%= button_to "#", remote: true, method: :delete, 
    class: "btn btn-xs btn-white" do %>
    <i class="fa fa-thumbs-up"></i> Liked this <%=  likeable.likes.count %>
<% end %>
<% else %>
<%= button_to polymorphic_path([likeable, @like]), remote: true,
    class: "btn btn-xs btn-white" do %>
    <i class="fa fa-thumbs-up"></i> Like <%= likeable.likes.count %>
<% end %>
<% end %>

create.js.erb

$("div#like-container-<%= @likeable.id %>").html("<%= j render partial: 'button_like', locals: { :likeable => @likeable } %>");

destroy.js.erb

$("div#like-container-<%= @likeable.id %>").html("<%= j render partial: 'button_like', locals: { likeable: @likeable } %>");

1 个答案:

答案 0 :(得分:0)

问题在于Like模型的验证

这一行

validates :likeable, presence: true, uniqueness: { scope: :likeable_id }

应该只是

validates :likeable, presence: true