我正在为我的应用程序添加一个分类功能,并为此而苦苦挣扎。通过分类,对象有许多类别。我正在尝试截取一个新分类的创建,检查是否有一个类似的分类,如果有,增加它的计数,如果没有,创建一个新的对象。这是我到目前为止所掌握的。
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
发布于 2010-05-22 17:28:02
这种逻辑不应该存在于控制器中。这是真正的业务领域,应该在模型中。下面是你应该怎么做:
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中有没有改变,但这是主要的想法
发布于 2010-05-22 11:08:04
我决定将其移出模型对象,并将其放入创建分类的控制器方法中。它现在可以工作了(耶!)如果有人感兴趣,这是代码。
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
https://stackoverflow.com/questions/2886778
复制相似问题