开发者

'has_one :through' association using namespaced classes

开发者 https://www.devze.com 2023-03-02 02:46 出处:网络
I am using Ruby on Rails 3 and I am trying to use an has_one :through association using namespaced classes. I read the official guide about association 开发者_如何学JAVAmodels but I don\'t know how to

I am using Ruby on Rails 3 and I am trying to use an has_one :through association using namespaced classes. I read the official guide about association 开发者_如何学JAVAmodels but I don't know how to accomplish that.

I have User, Relationship and Groupclasses and I would like to associate Users and Groups through the Relationship class. As well, I would like to autosave related records and delete the relationship records on group or user deletion.

My file system is:

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

In configs/routes.rb I have

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

Class (Model) statements are:

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

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

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

How I must write code associations in above model files? Have you some advice about?


UPDATE

My Classes (Models) have these attributes:

User

id

full_name

...

Relationship

id

user_id

group_id

Group

id

name


Your route namespacing has nothing to do with your model namespacing.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消