2012-07-25 64 views
0

这里是我的数据结构为什么过滤器之前给我一个错误

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 

class Position < ActiveRecord::Base 
    belongs_to :company 
    belongs_to :user 
    attr_accessible :company_id, :user_id, :regular_user 
    before_save :set_regular_user 

    def set_regular_user 
    if self.user.is_admin? 
     self.regular_user = false 
    else 
     self.regular_user = true 
    end 
    end 
end 

每次我跑

@user.companies << Company.last 

我得到ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved

,但如果我删除我之前过滤寄托都的作品完美并且如预期的那样保存

@user.companies << Company.last 
    Company Load (0.2ms) SELECT `companies`.* FROM `companies` ORDER BY `companies`.`id` DESC LIMIT 1 
     (0.1ms) BEGIN 
    SQL (0.2ms) INSERT INTO `positions` (`company_id`, `created_at`, `regular_user`, `updated_at`, `user_id`) 
     VALUES 
     (263, '2012-07-25 14:44:15', NULL, '2012-07-25 14:44:15', 757) 

任何想法我失踪....这个问题是基于此前question

回答

1

回调需要返回true为了继续,假取消操作。在你的函数中,if语句的值可能是false:self.regular_user = false ruby​​函数的返回值是最后一条语句。

只需将返回值添加到最后。

1

正如@DGM所说,回调总是在最后返回true(或者如果它们应该阻止代码继续执行,那么在流程中的某个点处为false)是一个好习惯。否则它可能会成为一些非常奇怪的错误来源(从经验来讲:))。

我怀疑是if分支返回false。希望如果你只是在回调中添加true作为最后一个语句,它应该可以工作。

相关问题