我想在 goal.rb
中做类似的事情 before_save :set_tag_owner,:if => [:create, :update]
def set_tag_owner
# Set the owner of some tags based on the current tag_list
set_owner_tag_list_on(self.user, :tags, self.tag_list)
self.tag_list = nil
end
我希望此方法在保存之前仅用于 goals_controller 的创建和更新操作。
否则我遇到标记问题,当目标被标记为已完成时,标记会消失,因为set_tag_owner
正在将其标记设置为nil
。
def mark_accomplished
@goal.update(accomplished: true)
end
def create
@goal = current_user.goals.build(goal_params)
@goal.save
respond_modal_with @goal, location: root_path, notice: 'Goal was successfully created! Go chase those dreams!'
end
def update
@goal.update(goal_params)
respond_modal_with @goal, location: root_path
end
我需要self.tag_list = nil
这一行,因为没有它,标记是双重渲染的
我还尝试通过before_action
回调在控制器中应用该目标模型逻辑,但即使我将undefined
更改为self
,我也收到@goal
错误。
答案 0 :(得分:2)
另一种方法是在模型中添加attr_accessor并使用它来停止before_save
一个例子
class Goal < ActiveRecord::Base
attr_accessor :dont_set_tag_owner
before_save :set_tag_owner, :unless => dont_set_tag_owner
def set_tag_owner
# Set the owner of some tags based on the current tag_list
set_owner_tag_list_on(self.user, :tags, self.tag_list)
self.tag_list = nil
end
end
然后,在控制器中
def mark_accomplished
@goal.update(accomplished: true, :dont_set_tag_owner => true)
end
而且,只是为了给你一个选择 - 根据你对updated_at的需求,你也可以这样做
def mark_accomplished
@goal.update_column(accomplished: true)
end