douvel
douvel

Reputation: 87

Filter elements from related table

Here are my tables

I'm currently displaying on my homepage all Current Bets (current is an option of status attribute) from all members. Here is my code:

<% @bets.where(status: "Current").each do |bet| %>
<%= bet.match_name %>
<%= bet.bet_choice %>
<% end %>

(where @bets = Bet.all in my Page controller)

What I would like to do is to display on my homepage all Current bets from members who are in the "team" (team is a boolean in User).

How can I do that?

Upvotes: 1

Views: 57

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

Assuming that, you have proper associations defined in your User and Bet models.

Try something like this:

User.where(team: true).joins(:bets).where('bets.status' => 'Current')

Update_1:

I see you have a column id_user in your bets table, which should be user_id instead, assuming your associations are like: User has_many bets and Bet belongs_to User.

Update_2:

If you want all such bets and then loop through the bets collection, then you have to modify the above query little bit like this:

Bet.where(status: "Current").joins(:user).where('users.team' => 'true')

Upvotes: 1

douvel
douvel

Reputation: 87

Here is the right code :

<% Bet.where(status: "Current").joins(:user).where('users.team' => 'true').each do |bet| %>

Thanks for the "joins" tip KM. It helped me well.

Upvotes: 0

Related Questions