I’m a newbie and loving rails but I’m stuck.
All I want to do is to be able to show in my “list.rhtml” view the
information between two tables who both have a HABTM relationship. So
this is what I have as follows.
TABLES
Projects
create_table “projects”, :force => true do |t|
t.column “title”, :string
t.column “description”, :text
end
Users
create_table “users”, :force => true do |t|
t.column “first_name”, :string
t.column “last_name”, :string
end
Projects_Users
create_table “projects_users”, :force => true do |t|
t.column “project_id”, :integer, :default => 0, :null => false
t.column “user_id”, :integer, :default => 0, :null => false
end
MODELS
class Project < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :projects
end
CONTROLLER
Projects_Controller
I have the generic scaffold running my list view
def list
@project_pages, @projects = paginate :projects, :per_page => 10
end
list.rhtml
I just want to be able to pull the projects and users that belong to
the project into a view.
Some projects may have 3 or 4 users.
so I have this
<% for project in @projects %>
<%= project.title %>
<%= project.users %>
<% end %>
Which outputs this when you run it…
Project 1
Project 2
Project 3
Project 4
Which from the database is somewhat accurate. I have two users in
“project 2” but for some reason ROR won’t let me access the information
about them so it only shows them as “##”, but those are users. Here is
my DB table below.
projects_users - DB
project_id user_id
1 1
2 2
2 3
3 1
What I want to achieve is something like this .
<% for project in @projects %>
<%= project.title %>
<%= project.users.first_name %>
<% end %>
**When I try to run this code above it gives me an error saying
undefined method `first_name’ for User:Class
The syntax looks somewhat correct, but I’m not doing it right.
Any help on my set-up I would appreciate it.