开发者

Datamapper - Find each client by project

开发者 https://www.devze.com 2023-01-10 22:08 出处:网络
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:

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 li开发者_Go百科ke 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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号