【问题标题】:Rails 4 grouped_collection_select with scopes for ordering带有订购范围的 Rails 4 grouped_collection_select
【发布时间】:2014-02-26 16:16:31
【问题描述】:

我曾经在 Rails 3.2.16 中使用过这段代码:

f.grouped_collection_select :state_id, @states.ordered, 'children.ordered', :name, :id, :name

升级到 Rails 4.0 后,我收到错误:

undefined method `children.ordered' for #<State:0x007f66498d90f8>

这似乎与作用域仅允许作为可调用对象有关。我的模型如下所示:

class State < ActiveRecord::Base
  has_many :children, class_name: 'State', foreign_key: 'parent_id'
  belongs_to :parent, class_name: 'State'

  scope :ordered, -> {
    order(:sequence)
       .order(:name)
  }
end

有人知道如何让这项工作再次发挥作用吗?我不能在这里使用 default_scope,因为它需要很多地方来覆盖这个默认范围。

【问题讨论】:

  • 你找到解决方案了吗?我有同样的问题。
  • 不,我已经创建了一个按顺序返回子级的函数,因此该函数结合了两个作用域。

标签: ruby-on-rails scope formbuilder


【解决方案1】:

您可能已经找到了这个问题的答案。但我认为您应该使用 grouped_collection_select 助手更改代码以调用 group_method:

f.grouped_collection_select :state_id, @states.ordered, :children, :name, :id, :name

来自 Rails 4 文档:

grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})

更新:

我要快速回答,你是对的。您可能需要使用default_scope 让它以您想要的方式工作?

【讨论】:

  • 您的回答对孩子有什么影响?问题是不能再使用 :ordered 范围了。
  • 查看我的更新,可能对您没有帮助。我将继续对此进行更多调查。奇怪的是你不能再使用 grouped_colelction_select 的范围了。
  • 查看原帖:“我不能在这里使用 default_scope,因为它需要很多地方来覆盖这个默认范围。”
【解决方案2】:

我已经通过创建一个结合两个作用域的函数children_ordered 解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-11
    • 2012-01-17
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多