简体   繁体   中英

ActiveRecord Query Conversion from Rails 2 to Rails 4.2

I am used to Rails 2 and have an existing query:

@players = Player.find(
  :all,
  :select => 'players.*, positions.name AS "position_name"',
  :joins => 'LEFT JOIN positions ON positions.id = players.position_id',
  :conditions => ['status IN (?, ?, ?, ?)', 'd', 'i', 'n', 'u']
)

I am trying to write the Rails 4 equivalent but I get an error unexpected ')', expecting keyword_end which is the closing bracket of the query.

@players = Player
  .select('players.*, positions.name AS "position_name"')
  .joins('LEFT JOIN positions ON positions.id = players.position_id')
  .where(status: ['d', 'i', 'n', 'u'])
)

I've tried reading the docs but can't see where I'm going wrong.

Also, if this were using the params hash instead of hardcoded values, would the above not be liable to sql injection, if so, how would it be written to use placeholders like the first Rails 2 query?

Drop the last ) ; that is an extra with the way the new query is structured.

@players = Player
  .select('players.*, positions.name AS "position_name"')
  .joins('LEFT JOIN positions ON positions.id = players.position_id')
  .where(status: ['d', 'i', 'n', 'u'])

will be considered as below without the new lines:

@players = Player.select('players.*, positions.name AS "position_name"').joins('LEFT JOIN positions ON positions.id = players.position_id').where(status: ['d', 'i', 'n', 'u'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM