2010-05-22 64 views
1

我正在为我的应用程序添加分类功能,并正在为此付出努力。对象通过分类有许多类别。我试图拦截创建一个新的分类,检查是否类似,如果是的话,增加它的数量,如果没有,创建一个新的对象。这是迄今为止我所拥有的。拦截新对象的创建

validate :check_unique 

    protected 

    def check_unique 
    categorization = Categorization.where(:category_id => self.category_id, :categorizable_id => self.categorizable_id, :categorizable_type => self.categorizable_type) 
    if categorization.first 
     categorization.first.increment(:count) 
    end 
    end 

回答

2

这种逻辑不应该存在于控制器中。这确实是业务领域,应该在模型中。这里是你应该如何去做:

categorization = Categorization.find_or_create_by_category_id_and_categorizable_id_and_categorizable_type(self.category_id, self.categorizable_id, self.categorizable_type) 
categorization.increment!(:count) 

find_or_create将试图找到在DB的类别,如果它不存在,它会创建它。现在只需确保计数默认为零,并且此代码将执行您想要的操作。 (当最初创建计数将在1,那么以后它会增加)

PS:我不知道,如果find_or_create在轨3.已更改,但是这是主要的想法

+0

好吧。这正是我所期待的,我只是不知道该怎么做。我真的不想把它放到任何控制器动作中,但这是一个快速解决方案。谢了哥们。 – amctammany 2010-05-22 15:22:25

+0

很高兴看到听到。如果这个答案对你有帮助,请考虑接受它。 – Faisal 2010-07-10 06:57:16

0

我决定将它从模型对象中移出并放入创建分类的控制器方法中。它现在可以工作(Yay!),如果有人感兴趣,这里是代码。

def add_tag 
    object = params[:controller].classify.constantize 
    @item = object.find(params[:id]) 
    @categories = Category.find(params[:category_ids]) 
    @categories.each do |c| 
     categorization = @item.categorizations.find(:first, :conditions => "category_id = #{c.id}") 
     if categorization 
     categorization.increment!(:count) 
     else 
     @item.categorizations.create(:category_id => c.id, :user_id => current_user.id) 
     end 
    end 
    if @item.save 
    current_user.update_attribute(:points, current_user.points + 15) unless @item.categorizations.exists?(:user_id => current_user.id) 
     flash[:notice] = "Categories added" 
     redirect_to @item 
    else 
     flash[:notice] = "Error" 
     redirect_to 'categorize' 
    end 
    end