4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

IDを使わず複合条件でhas_many

Posted at

やりたいこと

  • Town has_many :spots
  • Spot belongs_to :town
  • city_nameとtown_nameの2つのカラムで接続

こうしたらできました↓

Town.rb
class Town < ActiveRecord::Base
	has_many :spots, -> (object) { where(city_name: object.city_name)}, primary_key: :name, foreign_key: :town_name, class_name: 'Spot'
end

ポイント

  1. (object)でselfを引数に
  2. primary_keyとforeign_keyは条件が一つしかなくIDを使わない場合と同様に設定する

できてしまえば簡単ですが、ググってもやり方がすぐにわからず実験しながら解決しました。今後の参考になれば。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?