I'm running a search using the Ransack gem.
Controller code (for ItemsController)
@q = Item.search(params[:q])
@search_results = @q.result
After running the search, @search_results
contains multiple Items
(Item 1, Item 2, Item 3, …). Where each Item is a hash:
Item = { "id" => "12", "name" => "shovel", "user_id" => "2", "type" => "A" }
In this case, for each Item hash, I want to add an additional key-value pair that translates the user_id
into the name that is associated with that instance of the User
model (i.e., User has_many :Items
and Item belongs_to :Users
)
I tried in the same controller code section
@search_results.each do |item|
item[:user_name] = User.find_by_id(item.user_id).name
end
But I get an error that I can't write to item. I suspect Ransack has something to do with it though, because if I just print @search_results
, instead of getting the actual Item data, I get #<ActiveRecord::Relation::ActiveRecord_Relation_Item:0x000001025e6c78>
Help greatly appreciated!
Btw, in case there's even an easier way, the reason I want to add another key/value pair with the user_name is because the ultimate output is a JSON that is being picked up by another part of the codebase, and we don't want to run two separate database queries.