尝试在我的应用中创建多态关联的实例时出现此错误。我的想法是,我可以添加喜欢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
<% 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 %>
$("div#like-container-<%= @likeable.id %>").html("<%= j render partial: 'button_like', locals: { :likeable => @likeable } %>");
$("div#like-container-<%= @likeable.id %>").html("<%= j render partial: 'button_like', locals: { likeable: @likeable } %>");
答案 0 :(得分:0)
问题在于Like模型的验证
这一行
validates :likeable, presence: true, uniqueness: { scope: :likeable_id }
应该只是
validates :likeable, presence: true