Set values ​​of nested parameters before_base in rails

I have a Request model and a nested model for it fill_cartridges.

has_many :filled_cartridges, inverse_of: :request, dependent: :destroy
accepts_nested_attributes_for :filled_cartridges, reject_if: proc { |attributes| attributes['title'].blank? },allow_destroy: true

Run codeHide result

And my strong parameters:

def request_params
  :filled_cartridges_attributes => [:client_id,:cartridge_name,:cartridge_id,


Run codeHide result

Using this method, I assume my nested model is autosave when the parent (query) model is saved. And there may be many filled_pictures.

What I want to do is set the client_id and cartridge_id before_validation, if I don't, they won't work with a zero limit. I believe before_validation calls some method before every validation of the object. Therefore I believe that before_validation will call my method before validation for all nested objects.

This is how I am trying to use before_validation:

before_validation :set_attributes, only: [:create]

  def set_attributes
	@client = Client.where("name = ?", # this is  a problematic
	@cartridge = Cartridge.where('cartridge_name=?', self[:filled_cartridges_attributes][:cartridge_name].take # this is too
	self.client_id =
	self.cartrdige_id =

Run codeHide result

In the first two lines of set_attributes, I want to find my client and cartridge objects first. And for this I want to use values ​​from strong_params. How can i do this?


source to share

All Articles