この質問はほぼ答えていますが、それでもやり過ぎだと思います。 Rails の has_many 関係の問題
私は本当にこの割り当てのような割り当てをしたいだけです
@user.browsing_location = location1
@user.home_location = location2
私は多くのグーグルを行ってきましたが、すべての情報が矛盾しているか、多対多の関係の設定について説明しており、中間テーブルを使用した方法について説明しています。しかし実際には、データベースに必要なのは、user テーブルにロケーション用の 2 つの異なる名前の id フィールドを持たせることだけです。次のようなものは機能しますか?
ユーザー クラス
class User < ActiveRecord::Base
#locations created by this user
has_many :locations, :foreign_key => :creator_id
#locations for browsing and visiting
belongs_to :browsing_location, :source => :location
belongs_to :home_location, :source => :location
end
ロケーション クラス
class Location < ActiveRecord::Base
#Users who are just browsing this location now
has_many :browsing_users, :foreign_key => :browsing_location_id, :source => :users
#Users who are living here now
has_many :home_users, :foreign_key => :home_location_id, :source => :users
#User who created this location
has_one :user
end
私のモデルのかなりの数がこのような関係を必要とするため、このために余分なテーブルを作成する必要は避けたいと思います。