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?
ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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? 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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With