RailsCasts Pro episodes are now free!

Learn more or hide this

Jonathan Norris's Profile

GitHub User: ThriceGood

Site: https://www.linkedin.com/pub/jonathan-norris/90/283/33a

Comments by Jonathan Norris

Avatar

I am finding it hard to get this working. It looks to me as if my code is exactly the same apart from naming.

User model

ruby
  has_many :representative_groupings
  has_many :representatives, :through => :representative_groupings
  has_many :inverse_representative_groupings, :class_name => "RepresentativeGrouping", :foreign_key => "representative_user_id"
  has_many :represented, :through => :inverse_representative_groupings, :source => :user

representative grouping model

ruby
class RepresentativeGrouping < ApplicationRecord
  belongs_to :user
  belongs_to :representative, :class_name => "User"
end

I didnt use a migration to make this table as I already had it, i just renamed the name table name to suit

mysql> describe representative_groupings;
+------------------------+------------+------+-----+---------+----------------+
| Field                  | Type       | Null | Key | Default | Extra          |
+------------------------+------------+------+-----+---------+----------------+
| id                     | bigint(20) | NO   | PRI | NULL    | auto_increment |
| representative_user_id | bigint(20) | YES  | MUL | NULL    |                |
| user_id                | bigint(20) | YES  | MUL | NULL    |                |
| created_at             | datetime   | NO   |     | NULL    |                |
| updated_at             | datetime   | NO   |     | NULL    |                |
+------------------------+------------+------+-----+---------+----------------+

i test it with code like this:

ruby
    @u1 = User.create(:username => 'john1')
    @u2 = User.create(:username => 'mike1')
    rg = @u1.representative_groupings.build(:representative_user_id => @u2.id)
    rg.save

and try to view it like so:

ruby
<ul>
  <% for group in @u1.representative_groupings %>
    <li>
      <%= group.representative %>
    </li>
  <% end %>
</ul>

<br>

<ul>
  <% for user in @u2.represented %>
    <li><%= user %></li>
  <% end %>
</ul>

but i get this error:

ruby
ActionView::Template::Error (undefined method `username' for nil:NilClass):
    3: <ul>
    4:   <% for group in @u1.representative_groupings %>
    5:     <li>
    6:       <%= group.representative.username %>
    7:     </li>
    8:   <% end %>
    9: </ul>

if i just print out the 'group':

[#<RepresentativeGrouping id: 11, representative_user_id: 2, user_id: 1, created_at: "2017-08-16 13:51:59", updated_at: "2017-08-16 13:51:59">]

and i can access its values, but it fails when i try to access the 'representative'.

I feel that its probably pretty close and that ive messed up a naming convention somewhere. Can anyone spot where the issue is?