mercredi 29 avril 2015

Set nested params values before_validation in rails

I have a model Request and nested model to it filled_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

And my strong params:

def request_params
 params.require(:request).permit(:name,:type,
  :filled_cartridges_attributes => [:client_id,:cartridge_name,:cartridge_id,
:request_id,:_destroy,:id],

end

Using this method I believe my nested model is autosave when parent (request) model is saved. And there may be many filled_cartridges.

What I want to do is to set client_id and cartridge_id before_validation happens, if I won't they they will fail in not null constraint. I believe before_validation calls some method before every object validation. So 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]
....

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

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

Aucun commentaire:

Enregistrer un commentaire