0

In my controller, I need to pluck a single, matching integer value and then create a record with that value in another table. In action, it looks like this:

  if Participation.where(ranking: "1")
      first = PointsAllocation.where(game_id: params[:game_id]).where(place: "1").pluck(:points)
      Stack.create(game_id: params[:game_id], user_id: current_user.id, chips: first)
    else

    end 

I have tested in the console that the first variable is definable. If I run PointsAllocation.where(game_id: "1").where(place: "1").pluck(:points), it will return:

SELECT "points_allocations"."points" FROM "points_allocations" WHERE "points_allocations"."game_id" = 1 AND "points_allocations"."place" = 1 => [10]

Ok, so it is correctly plucking what looks like an integer value for Points. I then want to use this points value and send it to the Chips column in the Stack table. When I run this, it will add a nil record even though first is defined, like so:

<Stack id: 1, game_id: 1, user_id: 1, chips: nil>

In troubleshooting, I thought maybe the issue here is that even though it looks like an integer (and Chips, I should add, is a t.integer attribute), maybe it's accidentally a string or something from pluck. So let's map this to an integer to be safe by adding map(&:to_i) after the pluck.

When I do that, it gets weirder, as it now returns:

<Stack id: 9, game_id: 1, user_id: 1, chips: 0>

So when I convert it to an integer, it changes 10 to a 0 and adds it to the table.

Where am I going wrong?

1 Answer 1

2

You may resolve it loading only one object instead ActiveRecord::Association:

first = PointsAllocation.where(game_id: params[:game_id]).where(place: "1").first
points = first.points 
Stack.create(game_id: params[:game_id], user_id: current_user.id, chips: points)

Problem is that AR trying convert incorrect values if they type different with column type:

Stack.create(chips: 10)
#=> <Stack id: ..., chips: 10>
Stack.create(chips: [10])
#=> <Stack id: ..., chips: nil>
Stack.create(chips: "10")
#=> <Stack id: ..., chips: 10>
Stack.create(chips: "first")
#=> <Stack id: ..., chips: 0>
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, just caught it. An alternative: after reading the documentation, pluck will return an array even if it is just one value. By using .first, it converts to an integer and can be used in the create method successfully. Thanks!

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.