[英]Undefined method `type' for Polymorphic Association
Undefined method `type' for Polymorphic Association. 多态关联的未定义方法“类型”。
My Polymorphic association with the models Follow, Dad and Mom gives me an error when writing a method to see if a user is already following one of them. 我与模型Follow,Dad和Mom的多态关联使我在编写一种方法来查看用户是否已经关注其中的一个方法时出现错误。
Here are all of my models and the method following
which is the problem. 这是我所有的模型以及随之following
的问题所在的方法。
Models 楷模
class User
has_many :follows
def following?(followable)
follows.where(followable_id: followable.id, followable_type: followable.type ).any?
end
end
class Mom
has_many :follows, as: :followable, dependent: :destroy
end
class Dad
has_many :follows, as: :followable, dependent: :destroy
end
Controller 调节器
@dad = Dad.find(params[:dad_id])
View 视图
<% unless current_user.following?(@dad) %>
<%= link_to({ controller: 'follows', action: 'create', id: @dad.id }, { method: :post }) do %>
Follow
<% end %>
<% end %>
Error 错误
NoMethodError - undefined method `type' for #<Dad:0xaf63038>:
activemodel (4.0.2) lib/active_model/attribute_methods.rb:439:in `method_missing'
activerecord (4.0.2) lib/active_record/attribute_methods.rb:155:in `method_missing'
app/models/user.rb:17:in `following?'
.................
This works if I get rid of followable_type
but that removes the reason for the method. 如果我摆脱了followable_type
,这将起作用,但是这消除了该方法的原因。 Why is this happening? 为什么会这样呢?
This line is the problem 这条线是问题
follows.where(followable_id: followable.id, followable_type: followable.type ).any?
Replace followable.type
with followable.class.name
用followable.type
替换followable.class.name
type
used to be a synonym for class
but this was deprecated. type
以前是class
的同义词,但已弃用。 Even if it hadn't been deprecated, you need to find records where followable_type is the name of the class, not the class itself. 即使未弃用它,您也需要查找记录,其中followable_type是类的名称 ,而不是类本身。
@MaxWilliams is correct although if you still want to use type
you just need to include the method in your model @MaxWilliams是正确的,尽管如果您仍想使用type
,则只需在模型中包括该方法
module Typeify
def type
self.class.name
end
end
class Mom
include Typeify
end
class Dad
include Typeify
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.