2

I'm trying to write an write this:

Team.last.players.sum("goals")

erb:

SELECT SUM("players"."goals") 
FROM "players" 
WHERE "players"."team_id" = $1  [["team_id", 2]]

how to rewrite this so that I could use it in a method:

def sql_search
  sql = "SELECT SUM \"players\".\"goals\" FROM \"players\" WHERE \"players\".\"team_id\" = $1 [[\"team_id\", #{self.id}"
  connection.execute(sql);
end

keep getting this error:

PG::SyntaxError: ERROR:  syntax error at or near "."
LINE 1: SELECT SUM "players"."goals" FROM "players" WHERE "players"....

Any ideas would be appreciated

2 Answers 2

2

You don't need to add \" in sql statement, just remove them.

def sql_search
    sql = "SELECT sum(goals) FROM players WHERE team_id = #{self.id};"
    connection.execute(sql);
end
Sign up to request clarification or add additional context in comments.

1 Comment

This seems right but a little explanation could help
0

Is there some reason that you want to hard code the SQL query? It's generally bad practice to use string interpolation to insert parameters to SQL queries because of SQL injection attacks. Instead it's recommended to use ActiveRecord's SQL query parameter binding like this:

user_input = 5
Player.where('team_id = ?', user_input).sum(:goals)

Basically what this does is insert the parameter 5 after sanitization. This means you're safe from attacks where a hacker attempts to insert arbitrary SQL into parameter variables attempting to return sensitive data or delete data entirely!

Comments

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.