Skip to main content

Working with Lists from a Database

Rails • Asked by Brad Morrical

Greetings, I am learing Ruby on Rails as I'm migrating a legacy app from PHP. I'm just a beginner in ROR, and having trouble setting up the simplest of relationships.

In simplest terms, I have a contracts table, which stores an int. That int refers to a list of items in another table.

'contracts' table:

+----------- +-----------------+
| ContractID | PaymentType     |
+------------+-----------------+
| 2          | 1               |
| 7          | 2               |
| 9          | 2               |
+------------+-----------------+ 

'payment_types' table:

+--------------------- +
| ID | PaymentType     |
+----+-----------------+
| 1  | Cash            |
| 2  | Check           |
| 3  | COD             |
+----------------------+ 
# frozen_string_literal: true

# Contract Class
class Contract < ApplicationRecord

  self.primary_key = 'ContractID'

  belongs_to :payment_type

end
# frozen_string_literal: true

# Payment Types List
class PaymentType < ApplicationRecord

  self.primary_key = 'ID'

  has_many :contracts

end

The structure is not following Rails sensible defaults because it's a legacy database. I've tried all types of associations (One to One, One to Many, Many to Many) yet each time the rails console will not save the record and provides the error:

contract = Contract.new
contract.PaymentType = 1
contract.save!

ActiveRecord::RecordInvalid (Validation failed: Payment type must exist)

Please help me. :(


So it turns out I that I got it working quite well. The fix was to ensure I cross-refrencened the contracts and payment_types models with the has_and_belongs_to_many association:

# class payment_type
has_and_belongs_to_many :contracts
# class contract
has_and_belongs_to_many :payment_types

No join table required, thanks and solved.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.