mysql - rails : Find all records matching condition for any of the associated objects

标签 mysql sql ruby-on-rails ruby activerecord

我有以下 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/

相关文章:

mysql - 如何使用具有特定名称的 MySQL 连接数据库中的两个表

php - Opencart支付网关开发

php - 无法从数据库中选择

mysql - Mysql 查询、排序、分组和性能所需的建议

ruby-on-rails - 使用 JS 响应 iframe 文件上传

ruby-on-rails - 为什么只有某些调用会使用 devise_token_auth 使 token 失效/替换

php - ZF2保存到多个表,(1)如果数据库错误则回滚更改(2)显示数据库错误

sql - LEFT JOIN 返回空结果集

R中使用data.table包进行SQL的 `case when ...`代码转换

ruby-on-rails - 如何在 mongoid 中使用或条件进行查询