ACTIVESCAFFOLD:列排序?
我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要您的模型中定义了belongs_to/has_many关联,那么ActiveScaffold将为您完成所有这些操作(包括按foo.name排序) - 不需要自定义帮助器方法:
这种方式对您的数据库也更友善,因为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:
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)