【发布时间】:2008-12-23 00:25:07
【问题描述】:
我正在建立一个网站,用户可以在其中跟踪他们收集的《龙与地下城》人物 (www.ddmdb.com)。此功能涉及的模型/关系如下:
用户:
- 身份证
- 登录(用户名)
- 一堆其他字段
微型:
- 身份证
- 姓名
- 数字(集合中的#,不计数)
- release_id(外键)
- 一堆其他字段和外键
所有权:
- id(这真的需要吗?)
- user_id
- miniature_id
- have_count
- 最喜欢的(布尔值)
我建立的相关关系如下:
用户:
- has_many :所有权
- has_many :miniatures, :through => :ownerships, :uniq => true, :conditions => "ownerships.have_count > 0"
- has_many :favorites, :through => :ownerships, :source => :miniature, :uniq => true, :conditions => "ownerships.favorite = true"
缩影:
- has_many :所有权
- has_many :owners, :through => :ownerships, :source => :user, :uniq => true, :conditions => "ownerships.have_count > 0"
所有权:
- belongs_to :user
- belongs_to :miniature
我有一个页面,用户既可以查看和更新他们的收藏,也可以查看其他用户的收藏。它包含网站上所有微缩模型的列表和每个旁边的文本框,用户可以在其中输入他们拥有的每个微缩模型的数量。此功能也存在于微型模型的子列表中(按类型、发布、大小、稀有度等过滤)
当用户创建帐户时,他们的所有权中没有任何条目。当他们使用收藏页面或微缩模型子列表更新他们的收藏时,我在所有权表中创建条目,仅用于提交页面上的微缩模型。因此,如果它是完整的收藏列表,我会更新所有迷你图(即使计数为 0),或者如果它是子列表,我只会更新那些微缩图。因此,在任何时候,我可能拥有的特定用户: - 没有所有权条目 - 一些微缩模型的条目 - 所有微缩模型的条目。
我遇到的问题是我不知道如何使用“Rails 方法”通过 LEFT JOIN 查询数据库,因此如果用户在所有权中没有微型条目,则默认为have_count 为 0。目前,当我遍历所有缩影时,我分别查询每个 user_id/miniature_id 组合,这显然效率很低。
查看:
<% for miniature in @miniatures %>
<td><%= link_to miniature.name, miniature %></td>
<td><%= text_field_tag "counts[#{miniature.id}]", get_user_miniature_count(current_user, miniature), :size => 2 %></td>
<% end %>
助手:
def get_user_miniature_count(user, miniature)
ownerships = user.ownerships
ownership = user.ownerships.find_by_miniature_id(miniature.id)
if ownership.nil?
return 0
else
return ownership.have_count
end
end
另一种解决方案是在用户注册时为所有微缩模型创建条目,但是当所有用户在注册后将新微缩模型添加到数据库时,我还必须为所有用户添加 0 have_count。这似乎有点复杂,但也许这是正确的方法?
在所有权表中没有该特定用户的条目的情况下,有没有办法进行连接并为缩影提供默认值?
【问题讨论】:
标签: sql ruby-on-rails activerecord performance