Before_save =多次更改默认值 [英] Before_save = Change default value for many to many
本文介绍了Before_save =多次更改默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮我弄清楚应该在我的change_default方法中放什么代码吗?
Can someone help me figure out what code I should put in my change_default method?
我希望能够做这样的事情...
I would like to be able to do something like this...
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.如果您有任何建议或需要检查的内容,请告诉我.
As you can see the update ran, but the default values are not set to false. If you have any recommendations or things I can check, please let me know.
推荐答案
需要排除正在修改的当前记录.添加了where.not子句
Needed to exclude the current record that is being modified. Added the where.not clause
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
这篇关于Before_save =多次更改默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文