![](/img/trans.png)
[英]Rails, polymorphic association - find records with non-dead associated records
[英]Rails: Find all records matching condition for any of the associated objects
我有以下Ruby on Rails实体:
播放列表:
class Playlist < ActiveRecord::Base {
:id => :integer,
:name => :string,
:created_at => :datetime,
:updated_at => :datetime,
:dimension => :string,
:title => :string,
:text => :string,
:price => :float,
:playlist_image_file_name => :string,
:playlist_image_content_type => :string,
:playlist_image_file_size => :integer,
:playlist_image_updated_at => :datetime,
:main => :boolean,
:action => :string,
:hairdresser_id => :integer
}
和关键字:
class Keyword < ActiveRecord::Base {
:id => :integer,
:name => :string,
:created_at => :datetime,
:updated_at => :datetime,
:preselected => :boolean
}
它们之间的关系非常简单:基本上,一个播放列表对象可以具有0个或多个关联的关键字。 这些是模型:
class Keyword < ActiveRecord::Base
has_and_belongs_to_many :playlists
end
class Playlist < ActiveRecord::Base
has_and_belongs_to_many :keywords
has_attached_file :playlist_image, styles: {medium: "500x500", small: "200x200", thumb: "40x40"}, default_url: "/system/playlist_default.jpg"
validates_attachment_content_type :playlist_image, content_type: /\Aimage\/.*\Z/
end
那可以让我做这样的事情:
Playlist.first.keywords
并检索与第一个播放列表相关的所有关键字。
现在,我想构建一个函数来返回所有具有某些单词作为关键字并且“ main”等于true的播放列表。 例如,所有具有关键字“ Summer”的播放列表。 我尝试过:
Playlist.where(:main => true).map{|x| x.keywords.include? "Summer"}
但这仅返回一个包含true或false的数组,具体取决于相关播放列表是否包含关键字“ Summer”,我正在寻找仅在该播放列表的关键字数组包含单词“ summer”的情况下返回整个播放列表的内容。 我该如何实现?
这样的事情应该起作用,使用includes
:
Playlist.includes(:keywords)
.where(playlists: {main: true}, keywords: {name: 'Summer'})
您应该创建范围以提高可重用性。
class Playlist < ActiveRecord::Base
has_and_belongs_to_many :keywords
scope :main, -> { where(main: true) }
scope :with_key_words, -> (key_words) { joins(:keywords).where(keywords: {name: key_words}) }
end
要使所有播放列表都满足您的要求,只需:
Playlist.main.with_key_words(['Summer'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.