我想查看客户的每个项目,但不确定如何使用Datamapper来获取此信息。我的关系设置如下:
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
我想输出如下列表:
客户1
客户2
从Datamapper中获取此功能的最佳方法是什么?视图模板的外观是什么?
由于
答案 0 :(得分:1)
# Find all clients (this should go in a controller of some kind)
@clients = Client.all # Maybe you want to order them here too
查看...
<% @clients.each do |client| %>
<%= client.name %>
<ul>
<% client.projects.each do |project| %>
<li><%= project.title %></li>
<% end %>
</ul>
<% end %>
答案 1 :(得分:1)
DataMapper没有foreign_key选项。这是:child_key
因此,您需要更改客户端模型
class Client
property :id, Serial
property :name, String
has n, :projects, 'Project', :child_key => [:company_id]
end
您可以按客户端迭代所有项目
<% Client.all.each do |client| %>
<%= client.name %>
<ul>
<% client.projects.each do |project| %>
<li><%= project.title %></li>
<% end %>
</ul>
<% end %>