Search code examples
ruby-on-rails-3joinmodel-associations

Searching a has_many :through association including the middle model


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.


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.