Topic: Question about a for loop in a has_many relationship
Sorry for the ultra-newbie question here, but I've been butting my head against this for a couple of days.
To teach myself RoR, I am working on a simple framework for a multiplayer online game. Because a user must log in with a password and such, I followed Sonjaya Tandon's "How to build a secured web application with Ruby on Rails." All it does is set up a simple "users" table with a salted-hashed password, which seemed to work pretty well for what I was wanting, and it's working swimmingly.
Now, I'd like to extend that so that a user can have many games. I have a games table, with the following tables: id, user_id, game. (I'm trying to keep it simple at this point.) What I would like is for when you log into the system, your current games are displayed.
I've linked the tables in my models: [code=user.rb]class User < ActiveRecord::Base
has_many :games
end[/code] [code=game.rb]class Game < ActiveRecord::Base
belongs_to :user
end[/code]
I've tried everything I can think of to show a list of the currently logged in user's games, to no avail. Here's my latest try: [code=index.rhtml]<h1>Welcome! <%= @user.username %> </h1>
<%= for @game in @user.games %>
<%= link_to @game.name, :controller => 'games', :action => 'show', :id => id %>
<%= end %>[/code] Without the for-loop, the page displays the @user.username just fine. What am I doing wrong, that I can show a detail of the user's games? Currently, it's erroring out:
compile error
../config/../app/views/workbench/index.rhtml:11: parse error, unexpected ')', expecting kDO_COND or ':' or '\n' or ';'
_erbout.concat(( for @game in @user.games ).to_s); _erbout.concat "\n"
^
../config/../app/views/workbench/index.rhtml:14: parse error, unexpected kEND
_erbout.concat(( end ).to_s); _erbout.concat "\n"
Could some kind soul out there in Rails-land help me out? Thanks in advance.
Last edited by Yekrats (2006-12-10 09:27:15)