尝试将counter_cache添加到自连接rails模型时出错

时间:2017-06-05 16:28:40

标签: ruby-on-rails ruby-on-rails-4 self-join counter-cache

 public static class Cart
 {
    public static string AddCartItem(this Dictionary<int, string[]> CartList, int pId)
    {
        products p = new products();     

        ProductOptions po = new ProductOptions(); 

        if (pId > 0)
        {
            p.GetDataById(pId); 
            po.GetDataByProductId(pId);
        }

        CartList = (Dictionary<int, string[]>)HttpContext.Current.Session["CartList"];

        int count = 1;


        if (p.ID > 0)
        {
            if (CartList.Count > 0)
            {
                foreach (KeyValuePair<int, string[]> item in CartList)
                {
                    if (item.Key == p.ID)
                    {
                        count = Convert.ToInt32(item.Value[0]) + 1;
                    }
                }
            }

            if (count > 1)
            {
                CartList[p.ID][0] = count.ToString();
            }
            else
            {
                string[] value = new string[] { count.ToString(), po.Options };
                CartList.Add(p.ID, value);
            }
        }

        HttpContext.Current.Session["CartList"] = CartList;

        return p.Name; 
    }


}

我正在尝试向class Product < ActiveRecord::Base belongs_to :parent, :class_name => 'Product', :foreign_key => :parent_id has_many :children, :class_name => 'Product', :foreign_key => :parent_id 列添加计数器缓存。我尝试过以下方法:

:children

还有:

belongs_to :parent, :class_name => 'Product', :foreign_key => :parent_id
has_many :children, :class_name => 'Product', :foreign_key => :parent_id, counter_cache: true

当我运行has_many :children, :class_name => 'Product', :foreign_key => :parent_id, counter_cache: :children_count

我收到以下错误:

Product.reset_counters(foo.id, :children)

我不了解有关counter_cache或自联接的基本信息吗?关于这一点的信息很少,并不适用于这种类型的自我加入。

1 个答案:

答案 0 :(得分:0)

现金应该属于类似的

class Child  < ActiveRecord::Base
  belongs_to :product, counter_cache: true
...

没有多少人

class Product < ActiveRecord::Base
  belongs_to :parent, :class_name => 'Product', :foreign_key => :parent_id
  has_many :children, :class_name => 'Product', :foreign_key => :parent_id

但数据库列仍应位于产品

通过此link阅读4.1.2.3以获取更多信息