Подтвердить что ты не робот

Rails before_create не метод запуска

Я пытаюсь вызвать метод непосредственно перед сохранением экземпляра. У меня есть модель User:

class User < ActiveRecord::Base

    has_secure_password
    attr_accessible :name, :first_surname,:second_surname,:email, :password, :password_confirmation,:number,:credit

    before_save{ self.email.downcase! }
    before_create :generate_auth_token

    default_scope order: 'users.created_at ASC'

    has_many :operations

    def consume(what,price,agent)
        self.operations.create(category:what,price:price, agent_id:agent)
    end
end

И каждый User имеет много Operation (обратите внимание на использование debuger pry через bind.pry:

class Operation < ActiveRecord::Base
  attr_accessible :agent_id, :comment, :postcredit, :precredit, :category, :user_id,:price
  validates_presence_of :user_id
  validates_presence_of :agent_id
  validates_presence_of :price
  validates_presence_of :precredit
  validates_presence_of :postcredit
  validates_presence_of :category
  #before_save :compute_prices, :on => :create
  before_create :compute_prices
  belongs_to :user

  private

  def compute_prices
      binding.pry
      user=User.find(self.user_id)
      self.precredit=user.credit
      #select whether adding or subtracting
      if self.category == 'credit'
          self.postcredit=self.precredit+self.price
      else
          self.postcredit=self.precredit-self.price
      end
      user.update_attributes(credit:self.postcredit)
  end
end

Я заполняю базу данных пользователями и операциями и тестирую ее с помощью консоли $rails c --sandbox. Тогда I:

>fi=User.first
>ope=fi.operations.create(category:'credit',price:12.2,agent_id:3)
#Now here the debugger should start and does not

Я пытаюсь использовать оба before_create и before_save, но никто не работает.

before_create :compute_prices
before_save :compute_prices, :on => :create

Единственная работающая функция - after_initialize :compute_prices, но она запускается после каждого find или инициализации.

Любые идеи?

Решение

Как объясняется как комментарий к первому ответу, решение было для пользователя before_validation (function), on: :create вместо before_save ....

4b9b3361

Ответ 1

Является ли ваша операция действительной? Жизненный цикл обратного вызова находится здесь: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html, и если проверка не выполняется, он не сможет получить обратные вызовы create