ActiveRecordでid以外によるアソシエーションを設定する
foreign_key:
と primary_key:
オプションを利用する。
# == Schema Information # # Table name: twitter_accounts # # id :bigint(8) not null, primary key # screen_name :string(255) not null # # Indexes # # index_twitter_accounts_on_screen_name (screen_name) UNIQUE # class TwitterAccount < ActiveRecord validates :screen_name, presence: true, uniqueness: true has_many :users, foreign_key: :twitter_screen_name, primary_key: :screen_name end # == Schema Information # # Table name: users # # id :bigint(8) not null, primary key # twitter_screen_name :string(255) class User < ActiveRecord end
twitter_account = TwitterAccount.first twitter_account.users.to_sql #=> "SELECT `users`.`id`, `users`.`twitter_screen_name` FROM `users` WHERE `users`.`twitter_screen_name` = 'takeyuweb'"