Reputation: 18855
iOS developer learning Rails here. Trying to query active record for records based on a has_many
relation's property. Apologies if this is simple but I just can't figure it out. I've read about and have been trying to use scope
, .where
, .joins
, but there are so many contradicting posts and blogs online I'm unsure which to use and what's correct...
On to the problem:
I have two ActiveRecord models:
class User < ActiveRecord::Base
has_many :items
end
and
class Item < ActiveRecord::Base
belongs_to :user
end
An item has a property title
, I am trying to find all of the User
s that have an item with a title
that is similar to some search parameter in string format.
I have managed to do such using a search for items and then .map
like this:
users_owning_item_in_search_parameter = Item.where{ (title =~ my{@search_param + "%"}) }.map! { |i| i.user }
(that syntax comes from the squeel gem.)
But that command returns an Array
when I want an ActiveRecord::Relation
, because I need to do some further filtering that requires this instance type.
Any help much appreciated.
Upvotes: 2
Views: 1118
Reputation: 3475
I think you're looking for something like this:
User.joins(:items).where('items.title LIKE ?', "#{@search_param}%")
You'll have to modify it a bit if you want to take advantage of squeel.
Upvotes: 6