ruby-on-rails – Rails多态的has_many:through
发布时间:2020-12-16 20:09:31 所属栏目:百科 来源:网络整理
导读:我从外部API中提取一些数据,并希望在本地缓存结果.我有一个类SearchTerm,我想通过表searchable_items与几个不同的ActiveRecord类型相关联.我很确定我正确地设置了表格,但我的协会中的某些内容必须是错误的. class Foo ActiveRecord::Base has_many :search_t
我从外部API中提取一些数据,并希望在本地缓存结果.我有一个类SearchTerm,我想通过表searchable_items与几个不同的ActiveRecord类型相关联.我很确定我正确地设置了表格,但我的协会中的某些内容必须是错误的.
class Foo < ActiveRecord::Base has_many :search_terms,:as => :searchable,:through => :searchable_items end class Bar < ActiveRecord::Base has_many :search_terms,:through => :searchable_items end class SearchTerm < ActiveRecord::Base has_many :searchables,:through => :searchable_items end class SearchableItem < ActiveRecord::Base belongs_to :search_term belongs_to :searchable,:polymorphic => true end 我希望能够做一些类似SearchTerm.find_by_term(‘SearchTerm’)的搜索项(它会返回一个Foo和Bar对象的数组),但是我收到错误 提前感谢您可以提供给我的任何见解! 解决方法
您需要向Foo,Bar和SearchTerm模型添加has_many:searchable_items关联,因为:through => :searchable_items选项是指该关联.
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |