3

我有一个复杂的模型,并希望在我对 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 等...

4

2 回答 2

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
于 2012-02-26T22:01:33.437 回答
0

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

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

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

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

https://github.com/stefankroes/ancestry

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

于 2012-02-29T22:50:42.560 回答