2

我正在使用counter_culture创建调查应用程序问题是每次添加公民时计数列不会自动更新我必须去控制台并运行 Citizen.counter_culture_fix_counts 下面是我的模型和控制器供参考我正在使用 rails 4 和嵌套属性

谢谢你的帮助

模型

class Familycard < ActiveRecord::Base
    has_many :citizens  , :dependent => :destroy
  accepts_nested_attributes_for :citizens, :allow_destroy => :true
end

class Citizen < ActiveRecord::Base
  belongs_to :familycard

  counter_culture :familycard, 
    :column_name => Proc.new { |model| "#{model.sex}_count"},
    :column_names => {
      ["citizens.sex = ? ", 'male'] => 'males_count',
      ["citizens.sex = ? ", 'female'] => 'females_count'
    }

  counter_culture :familycard

  counter_culture :familycard, 
    :column_name => Proc.new { |model| "#{model.job}_count"},
    :column_names => {
      ["citizens.job = ? ", 'Entrepreneur'] => 'Entrepreneurs_count',
      ["citizens.job = ? ", 'House wife'] => 'housewifes_count',
      ["citizens.job = ? ", 'Student'] => 'students_count',
      ["citizens.job = ? ", 'Veteran'] => 'veterans_count',
    }    

end

controller

class FamilycardController < ApplicationController
  def new
    @familycard = Familycard.new(:citizens => [Citizen.new])
  end

  def create
    @familycard = Familycard.new(familycard_params)
    if @familycard.save
      flash[:success] = "Data Saved" 
      redirect_to familycards_path 
    else
      render 'familycards/familycard_form'
    end
  end
4

1 回答 1

1

跟进我的问题的一些评论,我已经解决了上面的问题,下面是 gem 条件的示例代码

 counter_culture :parent_model, :column_name => Proc.new {|child_model| 
    if child_model.published_condition == 'CONDITION 1'
      "condition1_count"
    elsif child_model.published_condition == 'CONDITION 2'
      "condition2_count"
    elsif child_model.published_condition == 'CONDITION 3' 
      "condition3_count"               
    end
    }, :column_names => {
      ["child_models.published_condition = ?", 'CONDITION 1']   => 'condition1_count',
      ["child_models.published_condition = ?", 'CONDITION 2'] => 'condition2_count',
      ["child_models.published_condition = ?", 'CONDITION 3'] => 'condition3_count'
     }

解释:

  • parent_model 有 3 个字段来保存总数,分别是 condition1_count、condition2_count 和 condition3_count
于 2017-06-28T15:27:27.280 回答