开发者

Rails 3: How to display data of multiple intra-dependent models in a table in the view?

开发者 https://www.devze.com 2023-03-20 05:06 出处:网络
I have a betting application, where users can bet on sports matches (e.g. basketball). I have something like this:

I have a betting application, where users can bet on sports matches (e.g. basketball). I have something like this:

Group has_many   :users
Group belongs_to :league
League has_many  :matches
Match has_many   :bets
User has many    :bets

Bet belongs_to :group
Bet belongs_to :match
Bet belongs_to :user

As you can see, users bet in groups. A group bets on one league (e.g. soccer season 2011/2012) and a league consists of many matches, that can be betted on.

I want to render the view for an action in the Group Controller (so Group is the base model). It should display a table with the matches on the horizontal table header and the users on the vertical table header. A table cell should show the bet of a user for the given match, like so:

       | Team 1 vs Team 2 | Team 3 vs Team 4
=======+==================+=================
User 1 |       1 : 2      |       0 : 0
-------+------------------+-----------------
User 2 |       2 : 0      |       1 : 0

Now the question is: how to best setup access to my data?

I could set up the @group attribute in the controller and then access data in the view like so:

<table>
  <thead>
    <tr>
      <th>&nbsp;</th>
      <% for match in @group.league.matches %>
        <th><%= "#{match.team1.name} vs. #{match.team2.name}" %></th>
      <% end %>
    </tr>
  </thead>
  <tbody>
    <% for user in @group.users %>
      <tr>
        <th><%= user.name %></th>
        <% for match in @group.league.matches %>
          <td><%= ?????? %></td>
        <% end %>
      </tr>
    <% end %>
  </tbody>
</table>

My problem is denoted with "??????": How to access the correct bet?

match.bets.find_by_group_id_and_user_id( ... ) # this will generate a new SELECT on DB
match.bets.to_a.find{|bet| bet.user_id == user.id && bet.group_id == @group.id}.home_score # seems cluttered and should no开发者_Python百科t belong in the view

Your input on this is greatly appreciated. Thanks!


This should work, if I'm understanding correctly:

<% for user in @group.users %>
  <tr>
    <th><%= user.name %></th>
    <% for match in @group.league.matches %>
      <% bet = Bet.find_by_user_id_and_match_id(user.id, match.id) %>
      <td><%= bet.whatever.. %></td>
    <% end %>
  </tr>
<% end %>

In response to your comment, you could put this stuff in a hash table in the controller like so:

@users = @group.users
@user_bets = @users.inject({}) do |hsh, user|
  hsh[user] = {}
  @group.league.matches.each do |match|
    hsh[user][match] = .. # look up the Bet and assign it here
  end
  hsh
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号