Forum: Ruby on Rails Primary and foreign key associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
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
end

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
end
add_index :locations, [:foreignapp_type, :foreignapp_id]
end

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.
This topic is locked and can not be replied to.