Ruby on rails 如何使用where方法查找数组rails中的所有内容id
在下面的代码中,“@search.sensors”是一个已搜索的数组。传感器属于出版物。有没有办法找到阵列中每个传感器的发布 出版模式Ruby on rails 如何使用where方法查找数组rails中的所有内容id,ruby-on-rails,Ruby On Rails,在下面的代码中,“@search.sensors”是一个已搜索的数组。传感器属于出版物。有没有办法找到阵列中每个传感器的发布 出版模式 class Publication < ApplicationRecord has_many :sensors, dependent: :destroy, autosave: true end 如果@search.sensors解析为Sensor类型的数组,则可以轻松执行以下操作: Publication.where(id: @search.se
class Publication < ApplicationRecord
has_many :sensors, dependent: :destroy, autosave: true
end
如果
@search.sensors
解析为Sensor
类型的数组,则可以轻松执行以下操作:
Publication.where(id: @search.sensors.map(&:publication_id))
你的
@search.sensors
函数看起来像什么?为什么它返回数组而不是ActiveRecord
关系?@jvillian是对的。如果它是一个ActiveRecordRelation(应该是imo),那么您只需选择
或清除
ID即可@search.sensors.pull(:publication\u id)或@search.sensors.select(:publication\u id)
@mikeheft-更像publication.joins(:sensors)。其中(sensors:{id:@search.sensors})
。
@sensors = @search.sensors
@publications = Publication.joins(:sensors).where(id: params[@search.sensors.map(&:id)])
@publications.uniq
Publication.where(id: @search.sensors.map(&:publication_id))