我有以下 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”,我正在寻找仅当该播放列表的关键字数组包含单词时才返回整个播放列表的内容“夏天”。我怎样才能做到这一点?
最佳答案
使用 includes
,这样的事情应该可行:
Playlist.includes(:keywords)
.where(playlists: {main: true}, keywords: {name: 'Summer'})
关于mysql - rails : Find all records matching condition for any of the associated objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37971862/