There is an action for that?

I'm trying to get all of the stocks that a user has. A user has stocks for different companies, so each line of the this table (Portfolio) you have the user_id company_id and the amount. So a user *has_many* portfolios. There is a way that I can get all of the *amounts* together ? Something that I can substitute the .first ? Something like .all ? Here is the code

<%= current_user.portfolio.**first**.amount %>

2 thoughts on “There is an action for that?”

  1. I’m assuming you meant `portfolios` as you mentioned it is a *has_many*.

    You would want to use [pluck](

    `<%= current_user.portfolios.pluck(:amount) %>`

    This functions just as you would expect [map]( to work, but is faster.

    When using `map` on ActiveRecord relations, all table data is fetched for each object in the relation, and a model for each row is instantiated before the desired column values are gathered.

    On the other hand, `pluck` will only fetch the values for the desired column from the table, and no models are instantiated.


Leave a Comment