質問

ユーザー モデル (:name、:password、:email)、イベント モデル (:name、:etc)、および興味モデル (:name) があります [>すべて単数形<]

次に、UsersInterests と EventsInterests という 2 つの結合テーブルを作成しました。それぞれに主キーは含まれず、それぞれ user_id/interest_id と events_id/interest_id のみで構成されます。[>複数<]

私のモデルは ネストされた多くのスループラグイン

user.rb => has_many :users_interests
 has_many :interests, :through => :users_interests
 has_many :events_interests, :through => :interests
 has_many :events, :through => :events_interests

event.rb => has_many :events_interests
  has_many :interests, :through => :events_interests
     has_many :users_interests, :through => :interests
  has_many :users, :through => :users_interests

interest.rb => has_and_belongs_to_many :users
               has_and_belongs_to_many :events

events_interests.rb => belongs_to :interests
                    belongs_to :events
users_interests.rb => belongs_to :users
                   belongs_to :interests

ふぅ…わかりました。そこで、特定のユーザーと関心を共有するすべてのイベントを検索するnamed_scopeを作成したいと思いました。これは誰かが私を助けてくれたコードです。

named_scope :shares_interest_with_users, lambda {|user|
{ :joins => :users_interests,
  :conditions => {:users_interests => {:user_id => user}}
   }}

コントローラーから実行する場合 =>

@user = User.find(1) 
@events = Event.shares_interest_with_user(@user)

エラーが発生します:

uninitialized constant Event::EventsInterest

誰か私が何を間違えたか見てもらえますか?

役に立ちましたか?

解決

途中で何か間違った名前を付けたに違いありません。一見すると、ファイルまたはクラスの名前が間違っていることがわかります。モデル名を覚えておいてください しなければならない ファイル名とクラス名の両方で常に単数形でなければなりません。そうしないと、Rails は接続を確立しません。問題のもう 1 つの原因は、belongs_to の引数も単数でなければならないことです。たとえ物事が正しく行われていたとしても、ユーザーとの関係における HABTM 関係により、名前付きスコープを実行するとエラーがスローされるでしょう。

以下のモデルでエラーを解決できました。

ユーザー.rb

class User < ActiveRecord::Base
has_many :users_interests
  has_many :interests, :through => :users_interests
  has_many :events_interests, :through => :interests
  has_many :events, :through => :events_interests
end

ユーザー_関心.rb

class UsersInterest < ActiveRecord::Base
  belongs_to :user
  belongs_to :interest
end

興味.rb

class Interest < ActiveRecord::Base 
  has_many :users,:through => :users_interests
  has_many :users_interests
  has_many :events_interests
  has_many :events, :through => :events_interests
end

**events_interest.rb

class EventsInterest <ActiveRecord::Base
  belongs_to :interest
  belongs_to :event
end

イベント.rb

class Event <ActiveRecord::Base 
  has_many :events_interests
  has_many :interests, :through => :events_interests
  has_many :users_interests, :through => :interests
  has_many :users, :through => :users_interests


  named_scope :shares_interest_with_users, lambda {|user|
    { :joins => :users_interests,
      :conditions => {:users_interests => {:user_id => user}}
    }
  }

end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top