3

私は少し複雑なモデルを持っており、レールについての私の限られた理解で完全な機能を実現したいと思っています。

セクション、ヘッダー(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に設定されている場合、is_shippableがfalseに設定されているかどうかをチェックするifステートメントを実行するにはどうすればよいですか?

編集-is_fragile、is_custom_sizeなどのis_shippableの機能もあります...

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)

いずれにせよ、祖先ははるかに表現力があり、確かに柔軟性が高くなります. 以下にリンクされている宝石の github wiki は、私が今まで見た中で最高のものです。非常によく整理されています。おそらくそれを熟読すると、さらにいくつかのアイデアが得られます。

https://github.com/stefankroes/ancestry

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

于 2012-02-29T22:50:42.560 に答える