简体   繁体   English

Rails多态关联不起作用

[英]rails polymorphic association doesn't working

I have model with polymorphic association. 我有具有多态关联的模型。

class Tag < ActiveRecord::Base
  #attributes target_id, target_type
  belongs_to :target, polymorphic: true
end

And Target model, which is user. 和目标模型,这是用户。

class User < ActiveRecord::Base
  has_many :tags, as: :target
end

But method @user = User.find params[:id]; @user.tags 但是方法@user = User.find params[:id]; @user.tags @user = User.find params[:id]; @user.tags returns #<ActiveRecord::Associations::CollectionProxy []> while Tag.where(target_id: @user.id, target_type: 'User') returns some objects I except. @user = User.find params[:id]; @user.tags返回#<ActiveRecord::Associations::CollectionProxy []>Tag.where(target_id: @user.id, target_type: 'User')返回一些对象,除了。

What's wrong? 怎么了?

这是错误的方法,因为它会给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

From an instance of the User model, you can retrieve a collection of tags like this: User模型的实例中,您可以检索这样的tags集合:

@user = User.find(params[:id])
@user.tags

Similarly, if you have an instance of the Tag model, you can get to its parent: 同样,如果您具有Tag模型的实例,则可以转到其父模型:

@tag.target

Problem was solved! 问题解决了!

I just add to model foreign_key . 我只是将模型添加到foreign_key

class User < ActiveRecord::Base
  has_many :tags, as: :target,
                  foreign_key: target_id
end

Thanks everyone, who try to help. 谢谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM