thedanotto
thedanotto

Reputation: 7327

Rails concatenate sql columns and create one to many relationship

I've got two models: Building and BuildingInfo. I want to relate the two tables using two columns townhall_level and name.

Ideally it will work like the following: Building.first.building_info For instance Building.first.townhall_level => 5 and Building.first.name => cannon, Building.first.building_info would access BuildingInfo.where(townhall_level: 5, name:"cannon".

What's the best way to do this? Can I create a third column which concatenates name and townhall_level? Could I also use that column to create the belongs_to and has_many relationship?

Upvotes: 3

Views: 176

Answers (2)

Francesco Belladonna
Francesco Belladonna

Reputation: 11729

Simple and straightforward:

class Building < ActiveRecord::Base

  def building_info
    BuildingInfo.find_by(townhall_level: townhall_level, name: name)
  end

end

It will be nil if nothing is found, and will return only the first record even if multiples are found. I also highly suggest that you add an index to the two columns through a migration:

add_index :building_infos, [:townhall_level, :name], name: 'building_infos_level_and_name'

Which will speed up searching, if you were concerned about performance.

Upvotes: 1

coorasse
coorasse

Reputation: 5528

mmm...I'm not sure 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 to put a building_info_id in the Building model and have a

class Building < ActiveRecord::Base
  belongs_to :bulding_info
end

Upvotes: 0

Related Questions