1

I am dealing with legacy code and do not have access to the database. There is a table which does not have a primary id column.

I can find a record using record = Model.find_or_initialize_by(listing_id: rating.pid, criteria_id: 33).

I can increment an attribute with record.rating_count += 1 but when I try to save it with record.save!, it gives the error TypeError: nil is not a symbol nor a string.

I think this is because record does not have a primary id (key) but I am not sure why it doesn't update the record.

If you have any suggestions, please let me know.

craig.kaminsky
  • 5,588
  • 28
  • 31
Murtza
  • 1,386
  • 1
  • 19
  • 27
  • Have you determined what exactly is `nil`? It *could* be that `rating.pid` is what is `nil` and `listing_id` is required in order to `save`. Hard to say without seeing model code, etc. but I'd, at least, start by trying to determine what exactly is `nil`. – craig.kaminsky Nov 17 '15 at 16:33
  • i have asked the company(maintaing the db) to make listing_id primary key. well, rating.pid is not nill, i have seen in the console and db. it have value 1445 andit exists in the db. when i try to save after increment than it shows error. – Murtza Nov 17 '15 at 16:36
  • In your Rails model, are there any `validate(s)` that might be causing the problem (i.e., `validate_presence_of :some_field`)? – craig.kaminsky Nov 17 '15 at 16:41
  • no, there is no validation. – Murtza Nov 17 '15 at 16:41
  • and there is no attribute `nil` – Murtza Nov 17 '15 at 16:42
  • 1
    Then it may, given the DB relations, etc., just be that you need a primary key (http://stackoverflow.com/questions/26568797/typeerror-nil-is-not-a-symbol) – craig.kaminsky Nov 17 '15 at 16:42
  • sounds like you are right but can i update this record with some mysql syntax? – Murtza Nov 17 '15 at 16:58
  • Yeah ... you'd need something to run raw SQL in (like Navicat or some similar program). – craig.kaminsky Nov 17 '15 at 17:11

1 Answers1

0

I also received the error TypeError: nil is not a symbol nor a string when trying to update a model which has no id column (or other primary key I could use). I had to add one.

You can add a primary key retrospectively using a migration:

    add_column :people, :id, :primary_key
Kris
  • 19,188
  • 9
  • 91
  • 111