好的,我有这个数据结构
Ok so i have this data structure
class User < ActiveRecord::Base has_many :companies, :through => :positions has_many :positions class Company < ActiveRecord::Base has_many :positions has_many :users, :through => :positions class Position < ActiveRecord::Base belongs_to :company belongs_to :user attr_accessible :company_id, :user_id, :regular_user end还有我的数据库结构
create_table "positions", :force => true do |t| t.integer "company_id" t.integer "user_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "regular_user", :default => true end如果我将另一家公司添加到用户公司,则regular_user 标志始终设置为 true
And if i add another company to a users companies, the regular_user flag is always set to true
1.9.3-p125 :013 > @userpanies << Company.last Company Load (0.3ms) SELECT `companies`.* FROM `companies` ORDER BY `companies`.`id` DESC LIMIT 1 (0.0ms) BEGIN SQL (0.2ms) INSERT INTO `positions` (`company_id`, `created_at`, `regular_user`, `updated_at`, `user_id`) VALUES (263, '2012-07-25 13:56:56', 1, '2012-07-25 13:56:56', 757)有没有办法在插入之前将标志设置为false
Is there a way to set the flag to false before the insert
我一直在通过这样做来解决它......这是hackish
I have been getting around it by doing this....which is hackish
@user.positions.update_all(:regular_user => false) if @user.is_admin?是否有另一种方法(更清洁)来实现这一目标
Is there another way (cleaner) to achieve this
推荐答案使用 before_save 过滤器.例如:
Use a before_save filter. Ex.:
class Position before_save :set_regular_user_to_false def set_regular_user_to_false self.regular_user = false end end就像过滤器名称所说的那样,这将在保存 position 对象之前拦截事件链,因此您可以更改 regular_user 属性.
Like the filter name says, this will intercept the chain of events right before saving the position object, so you can change the regular_user attribute.
编辑
def set_regular_user_to_false if self.user.user_type != 'admin' self.regular_user = false end true end更多推荐
有没有办法在 rails 中停止这个默认插入
发布评论