0

我试图让所有性别为男性或女性的@participants。我刚刚浮出水面,现在正在挖掘更多的可能性,但发现很难完成这个查询。

  • 用户 (user_id) has_profile
  • 个人资料属于用户
  • 参与者 (participant_id) 属于_to 用户、个人资料

我试图让所有具有参与者 ID 的参与者在个人资料( user_id )中的性别 = 'male' 或 'female'

让@participants_male 填满结果的最佳最短方法是什么?

我不知道如何摆脱与 where 语句的关系,任何人都可以帮助我朝着正确的方向前进吗?谢谢!

@participants_male = Participant.where(
4

2 回答 2

2

关于活动记录查询的 rails 指南是一个很好的资源。您的查询将如下所示:

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

或者你可以使用includes而不是joins

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

查看包含与连接,看看哪个适合您的特定情况。

于 2012-07-17T22:07:57.517 回答
2

性别是用户表中的一列?如果是这样的话:

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

编辑- 如果性别在配置文件表中:

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

我还建议检查joinsrailscast 以了解and之间的区别includes,以便您可以决定哪种情况更好。

于 2012-07-17T22:12:25.963 回答