Mar*_*tin 22 ruby ruby-on-rails ruby-on-rails-3
我刚刚创建了一个counter_cache字段,控制器看起来像这样.
@users = User.where(:sex => 2).order('received_likes_count')
Run Code Online (Sandbox Code Playgroud)
User.rb中的关联是
has_many :received_likes, :through => :attachments, :source => :likes, :dependent => :destroy
Run Code Online (Sandbox Code Playgroud)
问题是counter_cache是在Like.rb的belongs_to中声明的,我不知道如何告诉它是为了has_many:通过关联.
belongs_to :user, :counter_cache => :received_likes
Run Code Online (Sandbox Code Playgroud)
Aiv*_*oss 24
You have previous
class Product
has_and_belongs_to_many :categories
end
class Category
has_and_belongs_to_many :products
end
Run Code Online (Sandbox Code Playgroud)
and migration
class CreateCategoriesProducts < ActiveRecord::Migration
def change
create_table :categories_products, id: false do |t|
t.references :category
t.references :product
end
add_index :categories_products, [:category_id, :product_id]
end
end
Run Code Online (Sandbox Code Playgroud)
now change all to
class Product
has_many :categories_products, dependent: :destroy
has_many :categories, through: :categories_products
end
class Category
has_many :categories_products, dependent: :destroy
has_many :products, through: :categories_products
end
Run Code Online (Sandbox Code Playgroud)
and new one
class CategoriesProduct < ActiveRecord::Base
# this model uses table "categories_products" as it is
# column products_count is in the table "categories"
belongs_to :category, counter_cache: :products_count
belongs_to :product
end
Run Code Online (Sandbox Code Playgroud)
Eri*_* Hu 13
根据这篇文章(从上个月)和这篇文章(从2008年开始),它似乎不可能.但是,后一篇文章确实有解决方法的代码(为方便起见,从该链接复制/粘贴,在第二个链接中转到DEfusion)
class C < ActiveRecord::Base
belongs_to :B
after_create :increment_A_counter_cache
after_destroy :decrement_A_counter_cache
private
def increment_A_counter_cache
A.increment_counter( 'c_count', self.B.A.id )
end
def decrement_A_counter_cache
A.decrement_counter( 'c_count', self.B.A.id )
end
end
Run Code Online (Sandbox Code Playgroud)
(这是针对一个方案,其中C属于B,B属于A,A has_many C:通过=> B
| 归档时间: |
|
| 查看次数: |
12168 次 |
| 最近记录: |