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

好的,我有这个数据结构

class User  :positions has_many :positions class Company  :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

 1.9.3-p125 :013 > @user.companies << 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

我一直在做这件事….这是黑客

 @user.positions.update_all(:regular_user => false) if @user.is_admin? 

是否有另一种方式(清洁)来实现这一目标

使用before_savefilter。
例:

 class Position before_save :set_regular_user_to_false def set_regular_user_to_false self.regular_user = false end end 

与filter名称一样,这将在保存position对象之前拦截事件链,因此您可以更改regular_user属性。

编辑

 def set_regular_user_to_false if self.user.user_type != 'admin' self.regular_user = false end true end 

您可以直接插入一个位置

 user.positions << Position.new(company: Company.last, regular_user: false) 

老实说,自从我使用AR迁移以来已经有一段时间了,所以在生产数据库上运行之前请仔细检查我的语法。

话虽如此,这是在数据库级别上设置的,因为您的表结构已设置为true。 因此,如果存在NULL情况,它将成为真。

您应该能够运行将数据库列更改为默认值为false的迁移。 您也可以使用@MurifoX建议的回调覆盖,但我认为这可以更好地解决您的核心投诉。

祝好运!

 class ChangePostitionsRegularUser < ActiveRecord::Migration def up change_column :positions, :regular_user, :boolean, :default => false end def down change_column :positions, :regular_user, :boolean, :default => true end end