有人可以帮我弄清楚我应该在change_default方法中输入什么代码吗?
我希望能够做到这样......
user = User.find(1)
user.companies.first.default!
or
user.companies.find_by_company_id(2).default!
我的代码:
class Role < ActiveRecord::Base
before_save :change_default
belongs_to :user
belongs_to :company
def change_default
#update default field for to false for current scope
#Update current record default field to true
#this is what I currently have, but it's not setting my defaults to false
if self.default == true
roles = Roles.where( :user_id => self.user_id)
roles.update_all(:default => false)
end
end
def default!
self.default=true
self.save
end
end
class User < ActiveRecord::Base
has_many :roles
has_many :companies, :through => :roles
end
class Company < ActiveRecord::Base
has_many :roles
has_many :users, :through => :roles
end
代码运行:
pry(main)> a.roles.last.default!
(0.1ms) begin transaction
SCOPING
SQL (0.4ms) UPDATE "roles" SET "default" = 'f' WHERE "roles"."user_id" = 1
(2.0ms) commit transaction
=> true
[5] pry(main)> a.roles
=> [#<Role id: 1, company_id: 1, name: nil, view_document: nil, edit_document: nil, upload_document: nil, delete_document: nil, review_document: nil, company_info: nil, company_clients: nil, company_users: nil, company_admin: nil, created_at: "2014-08-04 20:10:23", updated_at: "2014-08-04 22:29:40", user_id: 1, default: true>,
#<Role id: 2, company_id: 2, name: nil, view_document: nil, edit_document: nil, upload_document: nil, delete_document: nil, review_document: nil, company_info: nil, company_clients: nil, company_users: nil, company_admin: nil, created_at: "2014-08-04 20:11:10", updated_at: "2014-08-04 20:11:10", user_id: 1, default: nil>,
#<Role id: 3, company_id: 3, name: nil, view_document: nil, edit_document: nil, upload_document: nil, delete_document: nil, review_document: nil, company_info: nil, company_clients: nil, company_users: nil, company_admin: nil, created_at: "2014-08-04 20:11:14", updated_at: "2014-08-04 22:29:16", user_id: 1, default: true>]
如您所见,更新已运行,但默认值未设置为false。如果您有任何我可以查看的建议或事项,请告诉我。
答案 0 :(得分:1)
需要排除正在修改的当前记录。添加了where.not子句
def change_default
if self.default_changed? && self.default == true
roles = Role.where( :user_id => self.user_id)
roles = roles.where.not(:id => self.id)
roles.update_all(:default => false)
end
end
答案 1 :(得分:0)
在示例中,您似乎永远不会在角色上调用save
。因此,您的before_save :change_default
未被执行。也许在role.save
中添加def default!
至少会执行before_save
因为我不确定您当前的控制台测试是否实际运行change_default
方法。
如果我错了并且它实际上正在运行,那么我不确定为什么你的块不会将default
值设置为false。