拦截新对象的创建

时间:2010-05-22 02:53:31

标签: ruby-on-rails validation

我正在为我的应用添加分类功能并努力解决它。对象通过分类有许多类别。我试图拦截新分类的创建,检查是否有类似的,如果是,增加它的计数,如果没有,创建一个新对象。这是我到目前为止所拥有的。

  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 个答案:

答案 0 :(得分: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将尝试在数据库中找到该类别,如果它不存在,它将创建它。现在只需确保count默认为零,此代码将执行您想要的操作。 (当最初创建时,计数将为1,然后它将增加)

PS:我不确定find_or_create是否在rails 3中发生了变化。但这是主要想法

答案 1 :(得分:0)

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

  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
相关问题