2

I've gotten close, I believe. My current query is this

items = Item.select("items.icon, items.name, item_types.name AS type, items.level, items.rarity, items.vendor_value")
.joins(:item_type)
.where("item_types.name = '#{params[:item_type]}'")

This gets me an array of Item objects that at least respond to :type with the item_type.name.

What I am looking for is an array of arrays that look so:

[icon, name, item_type.name, level, rarity, vendor_value]

I've already had it working fairly easily, but it is important to me that this be done in one fell swoop via sql, instead of creating a map afterwards, because there are times where I need to respond with 40k+ items and need this to be as fast as possible.

Not sure how to go from the above to an array of attributes, without performing a map.

Thanks for your help!

1 Answer 1

3

The pluck method does precisely what you want. In your case, it would look like this:

items = Item.joins(:item_type)
            .where("item_types.name = ?", params[:item_type])
            .pluck("items.icon", "items.name", "item_types.name AS type",
                   "items.level", "items.rarity", "items.vendor_value")

I also changed the where call to use parameterization instead of string interpolation—interpolation isn't recommended, especially when you're getting a value from the user.

Further reading:

Official documentation for pluck

An in-depth explanation of how to use pluck

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I've used pluck, but not with multiple values before. I didn't know it could do that. Very useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.