# can activerecord association with the functional foreign key

**URL:** <https://discuss.rubyonrails.org/t/can-activerecord-association-with-the-functional-foreign-key/68752>\
**Category:** rubyonrails-core\
**Created:** [March 27, 2014, 8:24am UTC](https://discuss.rubyonrails.org/t/can-activerecord-association-with-the-functional-foreign-key/68752 "2014-03-27T08:24:23Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![zhijia\_zhang](https://avatars.discourse-cdn.com/v4/letter/z/e47774/32.png) [@zhijia\_zhang](https://discuss.rubyonrails.org/u/zhijia_zhang)\
**Post date:** [March 27, 2014, 8:24am UTC](https://discuss.rubyonrails.org/t/can-activerecord-association-with-the-functional-foreign-key/68752/1 "2014-03-27T08:24:23Z")

</div>

As we know the model can associate other model through the foreign key which is assigned or with an “\_id” suffix by default. But can we define functional foreign key by ourselves ?

eg:

```ruby
  class Condition < ActiveRecord::Base
belongs_to :city_info, foreign_key: "substring_index(the_city,',',1)" end
class CityInfo < ActiveRecord::Base
end
>> Condition.includes(:city_info).references(:city_info).last
>> Mysql2::Error: Unknown column 'conditions.substring_index(the_city,',',1)' in 'on clause': SELECT ..... ......`conditions`.`substring_index(the_city,',',1)` ORDER BY `conditions`.`id` DESC LIMIT 1

```

It’s wrong. How can we achieve this.

I want to retrieve many conditions object, each associates with its first city\_info by ActiveRecord with generating a single sql (not n+1

) like this:

```ruby
select * from conditions left outer join city_info on convert(substring_index(conditions.the_city,',',1), unsigned integer) = city_info.id

```

`ref: https://github.com/rails/rails/issues/14481`
