Rails concatenates sql columns and creates a "one" relationship.
I have two models: Building
and BuildingInfo
. I want to link two tables using two columns townhall_level
and name
.
Ideally, it will work like this: Building.first.building_info
For example Building.first.townhall_level => 5
and Building.first.name => cannon
, Building.first.building_info
will have access to BuildingInfo.where(townhall_level: 5, name:"cannon"
.
What's the best way to do this? Is it possible to create a third column that concatenates name
and townhall_level
? Can I also use this column to create belongs_to and has_many relationships?
source to share
Simple and straightforward:
class Building < ActiveRecord::Base
def building_info
BuildingInfo.find_by(townhall_level: townhall_level, name: name)
end
end
This will be nil
if nothing is found, and will only return the first record, even if multiples are found. I also highly recommend adding an index on two columns via migration:
add_index :building_infos, [:townhall_level, :name], name: 'building_infos_level_and_name'
This will speed up searches if performance concerns you.
source to share
mmm ... I'm not sure if this will work, but you can do something like
class Building < ActiveRecord::Base
def self.bulding_info
BuildingInfo.find_by(townhall_level: townhall_level, name: name)
end
end
but I would really suggest you put building_info_id
in the building model and have
class Building < ActiveRecord::Base
belongs_to :bulding_info
end
source to share