Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass params from to a before_create in a model?

I have a model, for example :

class Account < ActiveRecord::Base

  before_create :build_dependencies

  def build_dependencies
    # use nifty params to build this related object
    build_nifty_object(params)
  end

The initial params are sent in through a hidden form tag on the Account#new form.

But there's no reason/need for these params to be saved to the account model. I just need them in the NiftyObject model.

Is there a clever way to pass these params to the before_create method ? Or any other alternatives that might accomplish the same task?

Thanks!

like image 818
Trip Avatar asked Oct 19 '25 22:10

Trip


1 Answers

You can use instance variables to workaround this, and do +1 step from the controller:

class Account < ActiveRecord::Base

  before_create :build_dependencies

  def assign_params_from_controller(params)
    @params = params
  end

  def build_dependencies
    # use nifty params to build this related object
    build_nifty_object(@params)
  end

In the controller:

  def Create
    account = new Account(params)
    account.assign_params_from_controller( ... )
    account.save   # this will trigger before_create
  end
like image 73
Matzi Avatar answered Oct 22 '25 01:10

Matzi