有没有办法在 rails 中停止这个默认插入

编程入门 行业动态 更新时间:2024-10-24 20:21:36
本文介绍了有没有办法在 rails 中停止这个默认插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

好的,我有这个数据结构

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 中停止这个默认插入

本文发布于:2023-10-28 13:34:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536778.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!