'has_one:through'使用命名空间类的关联

时间:2011-05-03 10:09:38

标签: ruby-on-rails ruby ruby-on-rails-3 class associations

我正在使用Ruby on Rails 3,我正在尝试使用名称空间类的has_one :through关联。我阅读了关于模型的official guide,但我不知道如何实现这一点。

我有UserRelationshipGroup个类,我想将UsersGroupsRelationship相关联类即可。同样,我想自动保存相关记录并删除关于组或用户删除的关系记录。

我的文件系统是:

app/models/users/user.rb
app/models/users/relationship.rb
app/models/users/group.rb

configs/routes.rb我有

namespace :users do
  resources :users
  resources :relationship
  resources :groups
end

Class(Model)语句是:

class Users::User < ActiveRecord::Base
  ...
end

class Users::Relationship < ActiveRecord::Base
  ...
end

class Users::Group < ActiveRecord::Base
  ...
end

我必须在上面的模型文件中编写代码关联吗?你有什么建议吗?


更新

我的类(模型)具有以下属性:

用户

ID

FULL_NAME

...

关系

ID

USER_ID

GROUP_ID

ID

名称

1 个答案:

答案 0 :(得分:4)

您的路线命名空间与您的模型命名空间无关。

class Users::User < ActiveRecord::Base
  has_many :relationships, :class_name=>"Users::Relationship", :dependent=>:destroy, :autosave=>true
  has_many :groups, :class_name=>"Users::Group", :through=>:relationships
end

class Users::Relationship < ActiveRecord::Base
  belongs_to :user, :class_name=>"Users::User"
  belongs_to :group, :class_name=>"Users::Group"
end

class Users::Group < ActiveRecord::Base
  has_many :relationsips, :class_name=>"Users::Relationship", :dependent=>:destroy, :autosave=>true
end