Forum: Ruby on Rails Primary and foreign key associations

7a096d30179ceb77d76d65c0eddc1d98?d=identicon&s=25 Charlie Lor (chuck)
on 2016-09-20 13:50
I need some clarifications on primary and foreign key. I have the
following tables.

def change
create_table :addresses do |t|
t.integer :location_id
t.string :street
t.string :street2
t.string :city
t.string :state
t.string :zip
t.timestamps null: false

def change
create_table :locations do |t|
t.integer :foreignapp_id
t.integer :foreignapp_type
t.integer :mailingaddress_id
t.integer :streetaddress_id
t.string :name
t.string :shortname
t.decimal :lat
t.decimal :lng
t.string :phone
t.string :email
t.string :fax
t.integer :room
t.integer :isactive, default:1
t.timestamps null: false
add_index :locations, [:foreignapp_type, :foreignapp_id]

In the Address model, I associated it with belongs_to :location and in
the Location model, I have:  has_many :addresses, dependent: :destroy at
the top. However, when I do myLocation.addresss.street I get a
NoMethodError: undefined method `address' for
#<Location:0x007ffe737471a0> error. However, if I do
myAddress.location.shortname it works. I thought once you specified in
the model, I should be able to request the information from either of
the two tables.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.