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
And my strong parameters:
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 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] .... 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 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
No one has answered this question yet
Check out similar questions: