Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord model without primary key

I have a ActiveRecord model GPA that doesn't have a primary key:

class GPA < ActiveRecord::Base

end

When I try to call GPA.first.to_json I get TypeError: false is not a symbol. I'm guessing that this is due to ActiveRecord trying to lookup the primary key. What is the correct way to implement a model without a primary key?

enter image description here

like image 812
Kyle Decot Avatar asked Sep 20 '13 18:09

Kyle Decot


People also ask

Can you use ActiveRecord without rails?

ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

Is ActiveRecord a framework?

1.3 Active Record as an ORM Framework Active Record gives us several mechanisms, the most important being the ability to: Represent models and their data. Represent associations between these models. Represent inheritance hierarchies through related models.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


2 Answers

Normally there is either some column or combination of columns which together do form a primary key. When you say your table doesn't have a primary key do you mean it doesn't have an id field?

Is there another column that is a unique/natural key? If so you can do:

class GPA < ActiveRecord::Base
  set_primary_key :strm    # eg column strm is a unique/natural key
end

You can also use composite keys with the composite keys gem, as follows:

class GPA < ActiveRecord::Base
  set_primary_keys :student_id, :strm
end
like image 52
Andrew Hacking Avatar answered Oct 02 '22 09:10

Andrew Hacking


Add a migration that adds id as a column. It's not going to hurt any existing code. Just make sure it's got an autoincrement on it so it's not going to moan about duplicate entry 0.

like image 42
Taryn East Avatar answered Oct 02 '22 08:10

Taryn East