1

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
3
  • where() returns a Relationship object (a scope) Commented Sep 29, 2012 at 7:16
  • Calling .first on a scope will returns the first object of that scope. Rails Active Record Guide: guides.rubyonrails.org/active_record_querying.html Commented Sep 29, 2012 at 7:18
  • You're aware, that in your controller you defined @rate but in your view you access @rates? Commented Sep 29, 2012 at 9:51

3 Answers 3

2
@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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 %>

2 Comments

Results in "undefined method `name' for nil:NilClass". Rate doesn't have a name column. What I'm trying to do is display the name of the Game whose id matches the Rate's "rateable_id".
Thank you, there ended up being another issue elsewhere but this is the correct solution.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.