Reputation: 6449
I have the following models:
rails generate model RoomType code:string description:text
class RoomType < ActiveRecord::Base
has_many :rooms
end
rails generate model room name:string code:string
class Room < ActiveRecord::Base
belongs_to :room_type, foreign_key: "code"
end
I want to reference Room
with RoomType
on code
and not room_type_id
.
So I do @room.room_type.description
in my rooms/show.html.erb
and I get undefined method description for nil:NilClass
RoomType
will only contain three codes i.e. AAA, BBB, CCC
Upvotes: 0
Views: 116
Reputation: 6449
Changed it to best practice (it is not best practice to use foreign key as string):
rails g migration add_room_type_id_to_rooms room_type_id:integer
class RoomType < ActiveRecord::Base
has_many :rooms
end
class Room < ActiveRecord::Base
belongs_to :room_type
end
Upvotes: 0
Reputation: 1555
Don't create a class called "Type". Change this name, maybe "Kind", I don't know.
Check this list Reserved words in rails
Upvotes: 3