ACTIVESCAFFOLD:列排序?

发布于 2024-12-01 02:57:10 字数 542 浏览 1 评论 0原文

我有 2 个模型说“foo”和“bar”,例如 foo has_many :bars,而 bar 属于 foo。它们都有一个“名称”字段。

active_scaffold :bar do |config|        
    config.columns = [:name, :foo_id]
    config.columns[:foo_id].label = 'Foo Name'
end

在控制器和助手中

def foo_id_column(b)
    return link_to b.foo.name, foo_url(b.foo)
end

这工作得很好,但是每当我单击表头“Foo Name”而不是按显示的名称排序时,它会按 foo_id 排序,也就是说,假设我们有 2 个 foo 对象“a ” 的 id 为 2,“b” 的 id 为 1,然后单击“FooName”列时,它首先显示为“b”行,然后是“a”,而不是“a”,然后是“b”。如何更改代码,使activescaffold使用名称内容而不是id进行排序?

I have 2 models say 'foo' and 'bar', such as foo has_many :bars, and bar belongs to foo. And they both have a 'name' field.

active_scaffold :bar do |config|        
    config.columns = [:name, :foo_id]
    config.columns[:foo_id].label = 'Foo Name'
end

in the controller and in the helper

def foo_id_column(b)
    return link_to b.foo.name, foo_url(b.foo)
end

And this works just fine but whenever I click on the table header "Foo Name" instead of getting sort by the name displayed it is getting sorted by the foo_id, meaning, say we have 2 foo objects "a" with id 2 and "b" with id 1, then on clicking the "FooName" column it is displaying as "b" row first then 'a' instead of 'a' then 'b'. How to change the code so that the activescaffold uses the name content instead of the id for sorting?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靑春怀旧 2024-12-08 02:57:10

只要您的模型中定义了belongs_to/has_many关联,那么ActiveScaffold将为您完成所有这些操作(包括按foo.name排序) - 不需要自定义帮助器方法:

active_scaffold :bar do |config|        
    config.columns = [:name, :foo]
end

这种方式对您的数据库也更友善,因为ActiveScaffold将:将关联包含到列出柱的查找器中,避免示例代码中出现的 N 查询问题(在渲染柱列表时分别获取每个 foo 记录)

As long as the belongs_to/has_many associations are defined in your models, then ActiveScaffold will do all of this for you (including sorting by foo.name) - no custom helper method needed:

active_scaffold :bar do |config|        
    config.columns = [:name, :foo]
end

This way is also kinder to your DB, since ActiveScaffold will :include the association into the finder for listing bars, avoiding the N-query issue that would be seen in your sample code (fetching each foo record separately when rendering the list of bars)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文