Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update ActiveRecord without id column

In a migration is a table without id column created:

create_table :drivers_companies, :id => false do |t|
  t.references :driver
  t.references :company
  t.string :last_sessionid
end

When saving a record:

dc = DriversCompany.where(company_id: 1, driver_id: 5)
if dc.length>0
  dc[0].last_sessionid = req.sessionID
  dc[0].save!
end

I get an error:

Mysql2::Error: Unknown column 'drivers_companies.' in 'where clause': UPDATE 'drivers_companies' SET 'last_sessionid' = 'bth49sv0outsehcg0ribuiu4h' WHERE 'drivers_companies'.'' IS NULL

How to update a record in table without ID column?

like image 664
Paul Avatar asked Jun 11 '14 08:06

Paul


1 Answers

ActiveRecord needs a primary key to do this. That can be a problem with legacy tables which can not be changed. You can not solve this without changing the table.

Sometimes one can use the "Composite Primary Keys for ActiveRecords" gem to solve it: https://github.com/composite-primary-keys/composite_primary_keys

like image 119
wintermeyer Avatar answered Oct 29 '22 21:10

wintermeyer