views:

85

answers:

2

Hi,

I'd like to view each Project by Client, but unsure how to use Datamapper to get this information out. I have my relationships setup like this:

class Client
    property :id, Serial
    property  :name, String
    has n, :projects, :foreign_key => "company_id"
end

class Project
  include DataMapper::Resource
  property :id, Serial
  property  :title, String
  belongs_to :company, "Client"
  has n, :stages
end

I would like to output a list like:

Client 1

  • Project A
  • Project B
  • Project C

Client 2

  • Project D
  • Project E

What's the best way to get this out of Datamapper and what would the view template look like?

Thanks

+1  A: 
# Find all clients (this should go in a controller of some kind)
@clients = Client.all # Maybe you want to order them here too

View...

<% @clients.each do |client| %>
<%= client.name %>
<ul>
  <% client.projects.each do |project| %>
  <li><%= project.title %></li>
  <% end %>
</ul>
<% end %>
rspeicher
That gives me a 'condition :foreign_key does not map to a property or relationship in MyApp::Project'Do I not need to do Projects.all() somewhere?
Tom
+1  A: 

DataMapper has not foreign_key option. It's :child_key

So you need change your Client model

class Client
    property :id, Serial
    property  :name, String
    has n, :projects, 'Project', :child_key => [:company_id]
end

After you can iterate on all project by client

<% Client.all.each do |client| %>
<%= client.name %>
<ul>
  <% client.projects.each do |project| %>
  <li><%= project.title %></li>
  <% end %>
</ul>
<% end %>
shingara
Thanks for your help so far, In the database my Projects table now has a company_id which is correct. However view is only outputting the the client name and nothing inside client.projects.each, any way I can debug?
Tom
Can you see which SQL command try to do DataMapper in log ?
shingara
Yep, I've got: ~ (0.000582) SELECT "id", "name", "client_slug" FROM "clients" ORDER BY "id" ~ (0.000094) SELECT "id", "title", "project_id" FROM "projects" WHERE "project_id" IN (2, 14, 15, 19, 20, 24, 28, 42, 43) ORDER BY "id""
Tom
And if you add 'Project' args in your has_n. I update my answers for that.
shingara