I’ve got an app that sets timed challenges for users. Each user is associated with one or more challenges. I’ve setup the models so they connect via a join table. That works fine, but I’m having problems on my view level. In the index view for the challenges, data from the challenge model and from the user model are displayed. But where the view should display the user’s name, it’s just displaying “User.” If you click on “User”, you are taken to the correct “show” page for that user. So the link works fine, but I can’t get the user’s name to appear. Instead, I’m just getting the class name to appear. Any idea why?
Here’s the code for the view. The file directly below is is views/challenges/index.html.erb
<%- model_class = Challenge.new.class -%>
<h1><%=t '.title', :default => model_class.model_name.human.pluralize %></h1>
<table class="table table-striped">
<thead>
<tr>
<th><%= model_class.human_attribute_name(:date) %></th>
<th><%= model_class.human_attribute_name(:time) %></th>
<th><%= model_class.human_attribute_name(:rider) %></th>
<th><%=t '.actions', :default => t("helpers.actions") %></th>
</tr>
</thead>
<tbody>
<% @challenges.each do |challenge| %>
<tr>
<td><%= link_to challenge.date, challenge_path(challenge) %></td>
<td><%= link_to challenge.duration, challenge_path(challenge) %></td>
<td><%= link_to challenge.users.name, user_path(challenge) %></td>
</tr>
<% end %>
</tbody>
</table>
And here’s the relevant models.
Challenge.rb
class Challenge < ActiveRecord::Base
attr_accessible :date, :duration, :user
has_many :user_challenges
has_many :users, :through => :user_challenges
validates_presence_of :date, :duration
def self.winner
Challenge.find(:first, :order => "duration desc")
end
end
User.rb
class User < ActiveRecord::Base
attr_accessible :name, :email
has_many :user_challenges
has_many :challenges, :through => :user_challenges
validates_presence_of :name, :email
validates_uniqueness_of :email
def self.find_or_create(name, email)
user = User.find_by_email(email)
if user.present?
user.challenge = challenge
user.save
else
User.create(:name => name, :email => email)
end
end
end
Join table, aka User_challenge.rb
class UserChallenge < ActiveRecord::Base
belongs_to :challenge
belongs_to :user
end
challenge.usersis a collection and.nameis a ruby method that gives you the name of the class:Call the attribute something else (username).
Also,
user_path(challenge)doesn’t really make sense when aChallengecanhave_many :users(which users path should it be?).