Reputation: 44086
Here is my 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
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
everytime i run
@user.companies << Company.last
I get ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved
but if i remove my before filter everthing works out perfect and it saves as expected
@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)
Any ideas what i am missing ....this question is based on this earlier question
Upvotes: 0
Views: 74
Reputation: 129
As @DGM says, it is good practice for callbacks to always return true at the end (or false at some point in the flow if they should prevent the code continuing). Otherwise it can be the source of some very odd bugs further down the line (speaking from experience :) ).
I suspect it is the if branch returning the false. Hopefully if you just add true as the last statement in the callback it should work.
Upvotes: 1
Reputation: 26979
Callbacks need to return true in order to continue, false cancels the operation. In your function, the value of the if statement may be false: self.regular_user = false
The return value of a ruby function is the last statement.
Just add a return true to the end.
Upvotes: 1