I’m writing a little recipe application, and I want my user profile
pages to list that particular user’s recipes.
I can’t figure out how to have the code say “Display all of the recipes
where the user_id column equals the id of this particular user profile”.
I know this is probably simple, but I haven’t written many loops without
copying off of other loops. 
Thanks!!
Dave
Hi –
On Fri, 10 Nov 2006, Dave A. wrote:
I’m writing a little recipe application, and I want my user profile
pages to list that particular user’s recipes.
I can’t figure out how to have the code say “Display all of the recipes
where the user_id column equals the id of this particular user profile”.
If you’ve done the “wiring” correctly (table and column names, model
names and associations), you should be able to do something like:
<% @user.recipes.each do |recipe| %>
… do stuff with recipe here …
<% end %>
This is predicated on:
-
a user_id column in the recipes table
-
this line in the user.rb model class:
has_many :recipes
-
this line in the recipe.rb model class:
belongs_to :user
And the assumption is that whenever you create a recipe, you assign a
user to it – like this:
recipe.user = user
or
user.recipes << recipe
All of this is just the basic (but very powerful) mechanism by which
ActiveRecord lets you use nice high-level Ruby commands, like
@user.recipes, to manipulate database-level relationships.
David
–
David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org
— models —
User < ActiveRecord::Base
has_many :recipes
end
Recipes < ActiveRecord::Base
belongs_to :user
end
— controller —
def user_profile
@user = User.find(params[:id]) # all prehaps get user from the
session
end
– view — (user_profile.rhtml)
<% @user.recipes.each do | recipe | -%>
<%= h recipe.name %>
<% end -%>
HTH,
Nicholas
Great, that was just what I was looking for. I had all of the “wiring”
right, and I knew there was an easy way to do it! Thanks!!