Ruby on rails 当我创建投票时,是否在post模型中触发保存回调?
我有一个后模型: 所有的标签都被移除了。我希望只有在编辑帖子时才会触发Ruby on rails 当我创建投票时,是否在post模型中触发保存回调?,ruby-on-rails,Ruby On Rails,我有一个后模型: 所有的标签都被移除了。我希望只有在编辑帖子时才会触发assign_标签。有什么建议可以解决这个问题吗 编辑: class VotesController < ApplicationController def vote_up @votable = params[:votable_type].constantize.find(params[:id]) if @votable.votes.exists?(:user_id => current_us
assign_标签。有什么建议可以解决这个问题吗
编辑:
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
投票\u控制器:
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
class VotesControllercurrent\u user.id)
@注意='你已经投票了'
其他的
@投票=@votable.vots.create(:user\u id=>current\u user.id,:polarity=>1)
@votable.reload
结束
回应待办事项|格式|
format.js
结束
结束
在没有回调的情况下更新帖子投票
模型-
def update_total
self.votable.total_votes += self.polarity
self.votable.send(:update_without_callbacks)
end
或
您可以使用“更新”列(名称、值),它跳过验证和回调-
def update_total
self.votable.update_column(:total_votes, votable.total_votes + polarity)
end
这里是修改后的投票模式
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
after_create :update_total
protected
def update_total
if votable && votable.is_a?(Post)
self.votable.update_column(:total_votes, votable.total_votes + self.polarity)
end
end
end
类投票true
属于:用户
创建后:更新总数
受保护的
def更新总数
如果votable&&votable.is_a?(Post)
self.votable.update_列(:total_投票,votable.total_投票+self.polarity)
结束
结束
结束
在提交后使用作为回调对不起,我有点困惑。您是要我删除update\u total
中的所有代码,并将其替换为上面的代码吗?(我试过了,但是总投票数没有更新)。谢谢你的帮助。我尝试了一下,得到了这个错误:NoMethodError(未定义的方法
update\u而不为#回调):app/models/vote.rb:11:inupdate\u total'app/controllers/votes\u controller.rb:8:in
vote\u up`。我在编辑中添加了vows\u controller.rb
。也许有什么东西可以让你了解这个问题。@alexchenco你能试试答案底部更新的vote
model吗!你是个天才。嘿,但顺便说一下,我有一个评论模式,也是可供选择的。我如何修改上面的代码来解决这个问题?添加条件if[Post,Comment]。include?(votable.class)
来更新列方法,以便对这两个模型进行更新
def update_total
self.votable.total_votes += self.polarity
self.votable.send(:update_without_callbacks)
end
def update_total
self.votable.update_column(:total_votes, votable.total_votes + polarity)
end
class Vote < ActiveRecord::Base
belongs_to :votable, :polymorphic => true
belongs_to :user
after_create :update_total
protected
def update_total
if votable && votable.is_a?(Post)
self.votable.update_column(:total_votes, votable.total_votes + self.polarity)
end
end
end