首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >截取新对象的创建

截取新对象的创建
EN

Stack Overflow用户
提问于 2010-05-22 10:53:31
回答 2查看 158关注 0票数 1

我正在为我的应用程序添加一个分类功能,并为此而苦苦挣扎。通过分类,对象有许多类别。我正在尝试截取一个新分类的创建,检查是否有一个类似的分类,如果有,增加它的计数,如果没有,创建一个新的对象。这是我到目前为止所掌握的。

代码语言:javascript
运行
复制
  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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-05-22 17:28:02

这种逻辑不应该存在于控制器中。这是真正的业务领域,应该在模型中。下面是你应该怎么做:

代码语言:javascript
运行
复制
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缺省为0,此代码将执行您想要的操作。(最初创建时,计数将为1,然后将递增)

PS:我不确定find_or_create在Rails3中有没有改变,但这是主要的想法

票数 2
EN

Stack Overflow用户

发布于 2010-05-22 11:08:04

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

代码语言:javascript
运行
复制
  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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2886778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档