1

私はレールに不慣れで、頭を動かすことができない状況にあります。

ユーザーとウィジェットの2つのリソースがあるとしましょう。

ユーザーはウィジェットを使用できますが、ウィジェットもユーザーが作成するものであり、ウィジェットを作成したユーザーが所有する必要があります。ユーザーがウィジェットを使用し、ユーザーがウィジェットを所有している必要があります。次は私が探しているものですか?

Class User < ActiveRecord::Base
  has_many :uses
  has_many :widgets, :through => :uses
  has_many :owns
  has_many :widgets, :through => :owns
end

Class Widget < ActiveRecord::Base
  has_one :own
  has_many :uses
  has_many :users, :through => :uses
end

Class Use < ActiveRecord::Base
  belongs_to :user
  belongs_to :widget
end

Class Own < ActiveRecord::Base
  belongs_to :user
  belongs_to :widget
end
4

1 に答える 1

1

少し違うやり方でやります。

Class User < ActiveRecord::Base
  has_many :uses
  has_many :widgets, :through => :uses
  has_many :owned_widgets, :class_name => "Widget"
end

Class Widget < ActiveRecord::Base
  belongs_to :owner, :class_name => "User"
  has_many :uses
  has_many :users, :through => :uses
end

Class Use < ActiveRecord::Base
  belongs_to :user
  belongs_to :widget
end

名前を少し変更しました。名前の競合がwidgetありました。同じ名前で2つの関連付けを行うことはできません。また、has_oneを削除し、クラスがに設定されownerたのforeign_keyを持つanを設定しました。それ以外は、多対多の関係をうまく設定します。owner_idUser

于 2010-07-15T01:40:27.137 に答える