selecting data with two join tables

You have to do it yourself in Ruby if you do it like that, or you will need to write some SQL.

class User < ActiveRecord::Base

def articles

@articles||= self.rights.collect{|right| right.articles.flatten}.flatten

end

end

That will allow you to do

u = User.find(1)

@articles = u.articles

Or you could write a more complex find_by_sql that would to that for you which may be more efficient.

I would add a .uniq! to the end as well since articles could belong to multiple rights and so could a user.

def articles

@articles||= self.rights.collect{|right| right.articles.flatten}.flatten.uniq!

end

-Bill

Brian Hogan wrote:

@William: Yeah. Good catch. I forgot to add that.

I’m pretty sure you can drop the first flatten and also, to avoid the n+1 query problem, adding :include would almost certainly be more efficient: `

def articles`

@articles||= self.rights.find(:all, :include => :articles).collect{|right| right.articles }.flatten.uniq!

end

-Bill

William Pratt wrote:

In your User model, add this:

def articles @article_list ||= self.rights.find(:all, :include =>:articles).collect{|right| right.articles }.flatten.uniq! end

Then in your controller, call the articles method on the current user. Say you have @user in your controller, then this would work:

@user.articles Note that the first method goes in the User model, not in your controller.

-Bill

Heldop Slippers wrote: