Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3: How to display data of multiple intra-dependent models in a table in the view?
    primarykey
    data
    text
    <p>I have a betting application, where users can bet on sports matches (e.g. basketball). I have something like this:</p> <pre><code>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 </code></pre> <p>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.</p> <p>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:</p> <pre><code> | Team 1 vs Team 2 | Team 3 vs Team 4 =======+==================+================= User 1 | 1 : 2 | 0 : 0 -------+------------------+----------------- User 2 | 2 : 0 | 1 : 0 </code></pre> <p><strong>Now the question is: how to best setup access to my data?</strong></p> <p>I could set up the @group attribute in the controller and then access data in the view like so:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;&amp;nbsp;&lt;/th&gt; &lt;% for match in @group.league.matches %&gt; &lt;th&gt;&lt;%= "#{match.team1.name} vs. #{match.team2.name}" %&gt;&lt;/th&gt; &lt;% end %&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;% for user in @group.users %&gt; &lt;tr&gt; &lt;th&gt;&lt;%= user.name %&gt;&lt;/th&gt; &lt;% for match in @group.league.matches %&gt; &lt;td&gt;&lt;%= ?????? %&gt;&lt;/td&gt; &lt;% end %&gt; &lt;/tr&gt; &lt;% end %&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>My problem is denoted with "??????": How to access the correct bet?</strong></p> <pre><code>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 &amp;&amp; bet.group_id == @group.id}.home_score # seems cluttered and should not belong in the view </code></pre> <p>Your input on this is greatly appreciated. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload