Reputation: 273
I'm very new to rails and putting together my first app. Please bear with me!
I'm making an app that lets the user rate the video games they are playing. On the site I've made a page where the user can see a list of all the games that he/she has rated in the past.
I'm running into some issues and I think it's pretty simple but it's driving me crazy.
In the controller I have:
def index
@rate = Rate.where(:rater_id => current_user.id)
@ratename = Game.where(:id => @rate.first.rateable_id)
end
And in my view I have:
<% @rates.order("created_at desc").each do |rates| %>
You are playing <%= @ratename.name %></div>
<% end %>
Where I'm confused is that in the browser this is displayed: "You are playing Game"
How do I get it to display the name of the game not just "Game"?
UPATE:
Model for rate:
class Rate < ActiveRecord::Base
attr_accessible :rateable_id, :rater_id
belongs_to :user
belongs_to :game
end
Upvotes: 1
Views: 268
Reputation: 1071
my suggestion just do this
in index
def index
@rates = current_user.rates.includes(:game).order("created_at desc")
end
in view
<% @rates.each do |rate| %>
You are playing <%= rate.game.name %></div>
<% end %>
this will solve your problem plus it will improve your server efficiency
Upvotes: 1
Reputation: 14205
Try referring to the associations directly.
Controller:
def index
@rates = current_user.rates.order("created_at desc")
end
View:
<% @rates.each do |rate| %>
You are playing <%= rate.game.name %>
<% end %>
Upvotes: 1
Reputation: 3742
@ratename = Game.where(:id => @rate.first.rateable_id)
means that you find Game with all attributes, not only name.
The right way:
in controller:
@rates = current_user.rates.order("created_at desc") #will work if you made correct associations (user has many rates)
in view:
<% @rates each do |rate| %>
You are playing <%= rate.game.name %></div>
<% end %>
rate.game.name will work if you made correct associations: game has many rates, rate belongs to game.
Upvotes: 2