【问题标题】:acts_as_tree and propagating a value through sub headers to itemsact_as_tree 并通过子标题将值传播到项目
【发布时间】:2012-03-07 07:00:54
【问题描述】:

我有一个稍微复杂的模型,并且希望在我对 Rails 的有限了解的情况下获得完整的功能。

我有一个部分、一个标题(使用acts_as_tree)和一个项目。

我使用 json 来引入数据集。这非常有效。我希望能够为整组数据(例如“is_shippable”)引入属性。我希望能够在树中的任何位置指定 is_shippable 值并将其设置为 true。另外,我希望能够在标题或项目级别覆盖以将其设置为 false。

我认为将 is_shippable 作为部分、标题和项目的属性是有意义的,并尝试使用 before_create 回调来确定它是否应该是 is_shippable。

例如:

section
  header -acts_as_tree
    item - is_shippable

示例 json:

{
 "name":"sample section",
 "is_shippable": true,
 "headers_attributes":[
   {
    "name":"sample_section"
    "items_attributes":[{
      "name":"sample item",
      "is_shippable":false,
           }
    ]       
   }
 ]

}

在 header.rb 中

before_save :default_values
private 
def default_values
  self.is_shippable ||=self.section.is_shippable
  # need to be able to set header to is_shippable=false if specified explicitly at that level    
end

在 item.rb 中

before_save :default_values


private 
def default_values
  # if not set, default to 0
  self.is_shippable ||= 0
  self.is_shippable=1 if self.header.is_shippable==true
  # need to be able to set item to is_shippable=false if specified explicitly at that level
end

有没有比我更好的方法来做到这一点?如果 is_shippable 在层次结构中被设置为 true,我将如何执行 if 语句检查 is_shippable 是否设置为 false?

编辑 - 还有更多 is_shippable 功能,例如 is_fragile、is_custom_size 等...

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 acts-as-tree


    【解决方案1】:

    我更倾向于在控制器中使用 before_filter 来修改嵌套项参数。

    类似:

    before_filter :set_is_shippable, :only => [:update, :create]
    
    def set_is_shippable
      is_shippable = params[:section][:is_shippable]
      params[:section][:items_attributes].each_with_index do |item, index|
        unless item[:is_shippable]
          params[:section][:items_attributes][index][:is_shippable] = is_shippable
        end
      end
    end
    

    【讨论】:

    • 种子用于为数据库播种,不消耗 json。如果您只播种一次数据,为什么不预处理 json 以获得正确的数据。如果你经常这样做,你应该建立一个解析模型。
    • 种子数据是 json。不是外部资源 - 不需要您正在讨论的内容
    【解决方案2】:

    我强烈推荐ancestry gem。它具有更多的树遍历方法,并且还优化了对数据库的查询次数。

    如果我正确理解您的困境,ancestry 将允许您执行以下操作:

    @section.descendants.all?(&:is_shippable)
    

    在任何情况下,祖先都更具表现力,并且肯定会给您更大的灵活性。下面为 gem 链接的 github wiki 是我见过的最好的。组织得很好,也许细读它会给你更多的想法。

    https://github.com/stefankroes/ancestry

    http://railscasts.com/episodes/262-trees-with-ancestry

    【讨论】:

    • 谢谢 - 我们的消息系统使用祖先。其中的一部分我真的很喜欢在应用程序级别,但是我们对这个模型中的数据库非常动手,我们想要使用acts_as_tree,因为模型更简单。但我们可能在这方面犯了一个错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多