Render array correctly in Rails

Asked

Viewed 48 times

0

I’m developing an application on Ails, but I ran into a problem that may be simple, but it’s killing me inside. I have an indicator on a screen that shows the number of credits that the selected coach has, and the number of coachees associated with the selected coach. In the coachs controller, in part Edit, I search for this information in the database as follows:

To find the amount of coachees associated:

@total_coachees = @current_account.coachees
  .where(coach_id: params[:id])
@act_coaches = (@total_coachees.activated.select(:id).count)

Getting the right result, and printing in the view with a simple @act_coachees, where the view displays only the desired number, 3

To get the amount of credits:

@total_cents = @current_account.coaches
  .where(id: params[:id])
@total = (@total_cents.select(:credits_available).to_a)

Printing in view as above, using @total However, the results are inconsistent, using .to_a at the end of the query, Rails prints in the view the following result:

[#<Coach id: nil, credits_available: 200>]

Changing to to_json, get:

[{"id":null,"credits_available":200}]

And by not putting any shape at the end, I get:

#<Coach::ActiveRecord_AssociationRelation:0x00007f7a341dbe50>

These results printed on the screen, the way they are presented here.

What am I doing wrong?

1 answer

0


Changing the search for:

@total = (@total_cents.select(:credits_available).to_a)

for:

@total = (@total_cents.pluck(:credits_available))

I can only find the column credits_available in the database, returning an array with an object, to render, I used

@total.first

*. first* being used to select the first object of the array, at the same time only one, or it prints the array with [] in the view.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.