嵌套有许多通过插件和命名范围

时间:2010-02-02 00:18:20

标签: ruby-on-rails relational-database has-many-through

我有一个用户模型(:名称,:密码,:电子邮件)和事件模型(:名称,等)和兴趣模型(:名称)[>所有单数<]

然后我创建了两个连接表 - >用户兴趣和活动兴趣;每个都不包含主键,并且分别仅包含user_id / interest_id和event_id / interest_id。 [>复数<]

我的模特使用Nested Has Many Through Plugin

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

Whew..ok所以我想创建一个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

任何人都可以看到我搞砸了什么吗?

1 个答案:

答案 0 :(得分:1)

你一定有错误的名字。我一眼就会说你的文件或类名不正确。记住模型名称必须总是单数,无论是文件名还是类名,否则Rails不会建立连接。你的问题的另一个来源是belongs_to的参数也必须是单数。即使你做得对,当你运行命名范围时,与用户有兴趣的HABTM关系也会抛出错误。

我能够使用以下模型解决您的错误。

user.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

<强> users_interest.rb

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

<强> interest.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

<强> event.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