我有一个后型号:在创建投票时触发post_sheet中的after_save回调?
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tag_names
has_many :votes, :as => :votable, :dependent => :destroy
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
attr_writer :tag_names
after_save :assign_tags
def tag_names
@tag_names || tags.map(&:name).join(" ")
end
private
def assign_tags
self.tags = []
return if @tag_names.blank?
@tag_names.split(" ").each do |name|
tag = Tag.find_or_create_by_name(name)
self.tags << tag unless tags.include?(tag)
end
end
end
一个标签型号:
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :posts, :through => :taggings
has_many :subscriptions
has_many :subscribed_users, :source => :user, :through => :subscriptions
def tag_posts_count
"#{self.name} (#{self.posts.count})"
end
end
和投票型号:
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
before_create :update_total
protected
def update_total
total_average = self.votable.total_votes
self.votable.update_attribute(:total_votes, total_average + self.polarity)
end
end
正如你可以在此看到最后一个型号,它更新了:total_votes
a每次创建投票的新实例时,都会发布帖子的属性。
出于某种原因,此操作正在触发后期模型中的after_save :assign_tags
操作。所以每次我创建一个投票的这个部分被称为:
def assign_tags
self.tags = [] // I added this so that the previous array of tags are removed before the new ones are added.
并且所有的标签都被删除。我只想在编辑帖子时触发assign_tags
。任何建议来解决这个问题?
编辑:
votes_controller:
class VotesController < ApplicationController
def vote_up
@votable = params[:votable_type].constantize.find(params[:id])
if @votable.votes.exists?(:user_id => current_user.id)
@notice = 'You already voted'
else
@vote = @votable.votes.create(:user_id => current_user.id, :polarity => 1)
@votable.reload
end
respond_to do |format|
format.js
end
end
对不起,我有点困惑。你是否告诉我删除'update_total'中的所有代码并用上面的代码替换它? (我试过,但'total_votes'没有更新)。 – alexchenco 2012-03-10 08:48:55
它应该工作..看看编辑答案 – 2012-03-10 09:04:22
感谢您的帮助。我试过了,得到这个错误:'NoMethodError(undefined method' update_without_callbacks'for#): app/models/vote.rb:11:'update_total' app/controllers/votes_controller.rb:8 :在'vote_up'' 。我在**编辑**中添加了'votes_controller.rb'。也许有些东西可以让你了解这个问题。 –
alexchenco
2012-03-10 09:09:09