Question

First, the topic.

I have three models, which are linked between each other with a has_many :trough association like this:

#User model 

has_many :chars_del, :class_name => CharDelegated, :dependent => :destroy
has_many :chars, :through => :chars_del

#CharDelegated model
#has a field owner:integer

belongs_to :char
belongs_to :user

#Char model
#has fields name:string

has_many :chars_del, :class_name => CharDelegated
has_many :users, :through => :chars_del

What I need to do is I need to search from a User Record to find all the Chars that the particular user ownes (:owner field is true) ordered by name. I have been stuck with this for a couple hours now, so I believe that I could have missed a very simple answer... But nothing that I have tried so far did work even a bit.

UPDATE found something that works:

user.chars.where(:char_delegateds => {:owner => 1}).order('name')

don't know why the :chars_del gave an error, but the full table name did the job.

Andrew, your answer works well too and is a little faster on the database, thans alot.

Was it helpful?

Solution

Does

user.chars.order('name')

not work? (Given user is a single User instance.)

Edit

Given your new information:

CharDelegated.where(user_id: user.id, owner: true).map(&:char)

should work.

OTHER TIPS

In your specific example you don't need to search through the middle table but if you want to see an example of how to use the joining table and search through it for a more complex scenario you can do it this way.

@char = Char.all(:include => :users, :conditions => ["char_delegated.user_id in (?)", user_id]).order('name')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top