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
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 = falseThe return value of a ruby function is the last statement.Just add a return true to the end.