开发者

:has_many relationship with :through on another relationship with :through

开发者 https://www.devze.com 2023-01-25 18:10 出处:网络
My setup is as follows: class User < ActiveRecord::Base has_many :owners, :dependent => :destroy has_many :properties, :through => :owners

My setup is as follows:

class User < ActiveRecord::Base
  has_many :owners, :dependent => :destroy
  has_many :properties, :through => :owners
end

class Owner < ActiveRecord::Base
  belongs_to :user
  belongs_to :property
end

class Property < ActiveRecord::Base
  has_many :owners, :dependent => :destroy
  has_many :users, 开发者_C百科:through => :owners
  has_many :datafiles, :dependent => :destroy
end

class Datafile < ActiveRecord::Base
  belongs_to :property
end

Now I'd like to be able to do @user.datafiles. I tried has_many :datafiles, :through => :properties, :source => :datafiles but there appears to be a problem with a :through on something that's already went to a :through. So how would I go about to try and manage what I'm trying to do here?

Thank you in advance.


2 approaches;

1>

class User < AR
  has_many :owners, :dependent => :destroy
  has_many :properties, :through => :owners
  has_many datafiles
end

class Datafile < AR
  belongs_to :user
  belongs_to :property
end

Your requirement of user.datafiles should be fulfilled with this.

If you want a nested has_many through, you'll need to use a plugin which is the 2nd approach.

2> You can find it here. The plugin works out of the box and does the job.


How about something like:

#user.rb

def datafiles
  Property.find(:all, :joins => :owners, :conditions => ['owners.user_id = self.id'], :include => :datafile).collect(&:datafile)
0

精彩评论

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