我使用最新的globalize2和rails 2.2。我想知道以下是错误还是功能:对于数据集中的每个项目,似乎都有一个单独的数据库查询来获取转换。这听起来不对,因为它可能很容易导致数百次查询。

插图。简单的控制器:

def index
    @menu_sections = MenuSection.find(:all)
end

然后@menu_sections在视图中循环,其中调用本地化属性(名称):

  <% @menu_sections.each do |menu_section| %>
    <p><%= link_to menu_section.name, :controller => 'store', :action => 'list_menu_items_for_section', :section_id => menu_section.id %></p>
  <% end %>

看起来每个menu_section.name都会导致db query:

Processing StoreController#index (for 10.0.2.2 at 2009-03-02 16:05:53) [GET]
  Session ID: 468f54928cbdc0b19c03cfbd01d09fa9
  Parameters: {"action"=>"index", "controller"=>"store"}
  MenuSection Load (0.0ms)   SELECT * FROM `menu_sections`
Rendering template within layouts/store
Rendering store/index
Rendered application/_js_includes (0.0ms)
  MenuSection Columns (0.0ms)   SHOW FIELDS FROM `menu_sections`
  MenuSectionTranslation Load (0.0ms)   SELECT * FROM `menu_section_translations` WHERE (`menu_section_translations`.menu_section_id = 1 AND (`menu_section_translations`.`locale` IN ('en','root')))
  MenuSectionTranslation Columns (0.0ms)   SHOW FIELDS FROM `menu_section_translations`
  MenuSectionTranslation Load (0.0ms)   SELECT * FROM `menu_section_translations` WHERE (`menu_section_translations`.menu_section_id = 2 AND (`menu_section_translations`.`locale` IN ('en','root')))
  MenuSectionTranslation Load (0.0ms)   SELECT * FROM `menu_section_translations` WHERE (`menu_section_translations`.menu_section_id = 3 AND (`menu_section_translations`.`locale` IN ('en','root')))
Completed in 340ms (View: 320, DB: 0) | 200 OK [http://www.dev.babooka.com/store]
你怎么看?也许有更好的方法在rails中转换db数据?

有帮助吗?

解决方案

你可以通过以下方式来完成你想要做的事情:

def index
    @menu_sections = MenuSection.find(:all,:include=>:globalize_translations)
end

那将急切加载翻译,因此,只会有2个查询。

其他提示

我不知道你是否重新解决了这个问题。但我遇到了同样的问题。我翻译了一个表格的一列(比如标题)。如果我在一个表中有100行,并且如果我对给定的语言环境执行这样的查询:

rows = Category.find(:all,.....)

这将导致数据库上的101个查询!!我不确定Globalize的设计者是否期望或打算这样做。

或者我遗漏了某些东西(就像查询中的可选配置参数一样)。

但是我确实找到了Saimon Moore的替代解决方案,他已经实现了全球化模型翻译的替代实施。您可以在以下网址阅读:

http://saimonmoore.net/2006 / 12/1 /替代的实现-的-全球化-模型翻译

但是如果这适用于Globalize2,我找不到任何引用。

我正在抛出Globalize2插件并使用Ruby I18N库推出自己的解决方案。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top