Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Article.find 1 raises ActiveRecord::StatementInvalid on legacy database

I'm creating a rails app over a legacy database table. Everything works fine locally, but on the server I hit this error whenever I do Article.find(1)

Could not log "sql.active_record" event. NoMethodError: undefined method `name' for nil:NilClass
ActiveRecord::StatementInvalid: PG::Error: ERROR:  zero-length delimited identifier at or near """"
LINE 1: SELECT  "articles".* FROM "articles"  WHERE "articles"."" = $1 LIMIT 1

The legacy database has an id field, however the schema describes the id with

create_table "articles", :id => false, :force => true do |t|
  t.decimal  "id", :precision => 10, :scale => 0, :null => false
  ...

Note that Article.find_by_id(1) returns the record without any problem.

Any ideas how to fix this?

like image 806
user208769 Avatar asked May 14 '13 11:05

user208769


2 Answers

UPDATED - See below

It turns out, adding the following to the model fixes this:

class Article < ActiveRecord::Base
  set_primary_key :id 
  ...

Presumably, because rails didn't create the table, it doesn't know what field the primary key is. It seems a little odd though, an educated guess with a warning - or even a more friendly error message - would be appreciated.

UPDATE: Rails 3.2+ the above method is deprecated. The new method is as follows:

class Article < ActiveRecord::Base
  self.primary_key = :id 
  ...

Thanks to @lboix for pointing this out!

like image 185
user208769 Avatar answered Jan 04 '23 10:01

user208769


Seems that this option has been updated guys : set_primary_key error in Rails

Hope it will help :)

Take care

like image 20
lboix Avatar answered Jan 04 '23 12:01

lboix