0

Im trying to get all the @participants where gender is male or female. I have just surfaced AR and now digging into all the possibility's more but find it hard to get this query done.

  • user (user_id) has_profile
  • profile belongs_to user
  • participants (participant_id) belongs_to user, profile

Im trying to get all the participants with participant_id where in there profile ( user_id ) they have gender = 'male' or 'female'

What would be the best shortest way to get the @participants_male filled with the results?

Im not sure how to get it out of the relations with the where statement, anyone could help me in the right direction? thx!

@participants_male = Participant.where(
Rubytastic
  • 15,001
  • 18
  • 87
  • 175

2 Answers2

2

The rails guides on active record queries is a good resource. Your query would look something like this:

@males = Participant.joins(:profiles).where('profiles.gender = "male"')

Or you can use includes instead of joins

@males = Participant.includes(:profiles).where('profiles.gender = "male"')

Take a look at includes vs joins to see which is appropriate for your particular case.

Community
  • 1
  • 1
Dty
  • 12,253
  • 6
  • 43
  • 61
2

The gender is a column in the users table? If so:

@participants_male = Participant.includes(:users).where("users.gender = 'male'")

EDIT - if gender is in the profiles table:

@participants_male = Participant.includes(:profiles).where("profiles.gender = 'male'")

I also suggest to check this railscast to understand the difference between joins and includes, so you can decide what is better in your case.

gabrielhilal
  • 10,660
  • 6
  • 54
  • 81
  • Ok So tried this and reading on joins vs includes. you example seems logic but throws an "Association named 'profiles' was not found; perhaps you misspelled it?" so its not associated for participant – Rubytastic Jul 17 '12 at 23:19
  • There is something wrong with your associations. Can you please include the models in your question... – gabrielhilal Jul 18 '12 at 07:22
  • Still this isn't working I think i should update question with more details on models and relations have to do that tonight – Rubytastic Jul 19 '12 at 09:45
  • yes, please clarify the relationship between participants and profiles, because you said `participant belongs_to profile` but you didn't state that `profile has_many (or whatever) participants`. How are they connected? – gabrielhilal Jul 19 '12 at 11:00