1

この質問はほぼ答えていますが、それでもやり過ぎだと思います。 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

私のモデルのかなりの数がこのような関係を必要とするため、このために余分なテーブルを作成する必要は避けたいと思います。

4

1 に答える 1

0

ロケーションクラス、browsing_locationとhome_locationを継承する2つのテーブルと、ユーザークラス、browsing_userとhome_userを継承する2つのテーブルを作成しようとしているようです。Rails 3の場合:

あなたは一般的な考えを持っていますが、あなたは物事を少し混乱させたようです。:sourceは、使用する関連付けを決定するために、多対多の関係に使用されます。代わりに必要と思われるのは:class_nameです

:foreign_key属性を正しく使用していることを確認するために、ユーザーと場所のテーブル定義を確認する必要があります。

user.rb

class User < ActiveRecord::Base
  # locations created by this user
  has_many :locations, :foreign_key => :creator_id

  # I'm assuming the locations belong to the user, as you're end goal was stated as  
  # the ability to call set user.browsing_location and user.home_location 
  # that would mean that browsing_location and home_location would need to belong to
  # the User class, not the other way around.  
  has_many :browsing_locations, :class_name => :location
  has_many :home_locations, :class_name => :location

end

class Location < ActiveRecord::Base

  # User who created the location
  belongs_to :user

  # Users who are just browsing this location now
  has_many :browsing_users, :class_name => :users
  # Users who are living here now
  has_many :home_users, :class_name => :users

end
于 2011-01-27T11:40:32.117 に答える