【发布时间】:2017-07-04 10:55:07
【问题描述】:
我有一个角色表
select * from roles;
id | name
----+----------
1 | admin
2 | user
3 | author
4 | guest
5 | manager
还有另一个表 user_roles
select * from user_roles;
role_id | user_id
---------+---------
3 | 1
3 | 2
3 | 3
4 | 5
3 | 6
5 | 7
5 | 8
1 | 9
1 | 11
#role.rb
class Role < ActiveRecord::Base
has_and_belongs_to_many :users, join_table: 'user_roles', class_name: user_class.to_s
end
我正在尝试在用户角色更新时执行一些操作,例如从 guest 到 author
#user.rb
class Use < ActiveRecord::Base
after_update :print_role_updated if: :user_roles_changed?
.
.
private
def user_roles_changed?
user_roles.any? { |role| role.changed? }
end
def print_role_updated
puts "User role changed from #{old_role} to #{new_role}"
end
end
但它没有按预期工作(.changed? 正在检查role 表中的值是否已更新?)。
每当用户角色更新为不同的角色时,我如何运行print_role_updated 方法?
编辑
我尝试了医生的回答,但即使记录正在更新,role_updated? 仍返回 false
class Use < ActiveRecord::Base
has_many :user_roles
after_update :print_role_updated if: role_updated?
.
.
private
def role_updated?
user_roles.any? {|a| a.changed?}
end
def print_role_updated
puts "User role changed from #{old_role} to #{new_role}"
end
end
【问题讨论】:
标签: ruby-on-rails ruby activerecord callback