[英]rails polymorphic association doesn't working
我有具有多态关联的模型。
class Tag < ActiveRecord::Base
#attributes target_id, target_type
belongs_to :target, polymorphic: true
end
和目标模型,这是用户。
class User < ActiveRecord::Base
has_many :tags, as: :target
end
但是方法@user = User.find params[:id]; @user.tags
@user = User.find params[:id]; @user.tags
返回#<ActiveRecord::Associations::CollectionProxy []>
而Tag.where(target_id: @user.id, target_type: 'User')
返回一些对象,除了。
怎么了?
这是错误的方法,因为它会给NameError: undefined local variable or method user for main:Object
提供错误NameError: undefined local variable or method user for main:Object
,首先您必须找到user,并且其标签如下:
@user=User.find(1)
@user.tags
从User
模型的实例中,您可以检索这样的tags
集合:
@user = User.find(params[:id])
@user.tags
同样,如果您具有Tag
模型的实例,则可以转到其父模型:
@tag.target
问题解决了!
我只是将模型添加到foreign_key
。
class User < ActiveRecord::Base
has_many :tags, as: :target,
foreign_key: target_id
end
谢谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.