2
votes

Hello all I am using cocoon gem to build nested forms.

has_many :filled_cartridges, inverse_of: :request, dependent: :destroy
accepts_nested_attributes_for :filled_cartridges, allow_destroy: true

This is my request model.

Inside request.html.erb I have:

<%= f.fields_for :filled_cartridges do |filled_cartridge| %>
   <fieldset class="nested-fields"> 
     <%= filled_cartridge.autocomplete_field :cartridge_name, autocomplete_cartridge_cartridge_name_requests_path, :update_elements => {} %>
     <%= filled_cartridge.hidden_field :_destroy %>
     <%= link_to_remove_association "удалить", f %>
   </fieldset>  
<% end %>

Strong Params:

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

So I have destroy and id params in order to be able destroy records. I want to handle my request and filled cartridges model in one instance. I believe I can do that thanks to accepts_nested_attributes.

The problem is that it cant save filled_Cartridge:

SQLite3::ConstraintException: NOT NULL constraint failed: filled_cartridges.client_id

I guess the problem is inside the controller method:

@request = Request.new( request_params )
@client = Client.where("name = ?", @request.name).take

if params[:request][:filled_cartridges_attributes].present? and params[:stype_ids].present?
    if params[:stype_ids].include? '1'
        params[:request][:filled_cartridges_attributes].each do |_,value|
            if @client.present?
                value[:client_id] = @client.id
            else
                value[:client_id] = 0
            end
                value[:request_id] = 0  #временный id
                @cartridge = Cartridge.where('cartridge_name=?', "#{value[:cartridge_name]}").take
            if @cartridge.nil?
                @cartridge = Cartridge.create!(:cartridge_name => "#{value[:cartridge_name]}")
        end
            value[:cartridge_id] = @cartridge.id
            value[:cartridge_name] = @cartridge.cartridge_name
        end
    end
end

NOTE: Can i set params like value[:parm] = something

1
Have you tried this ? <%= filled_cartridge.autocomplete_field :cartridge_name, autocomplete_cartridge_cartridge_name_requests_path, :update_elements => {} %> <%= filled_cartridge.hidden_field :_destroy %>Amit Sharma
@Amit Sharma, by the way it is just typo, the fieldset was initially in partial. Ignore ityerassyl
Why is this question tagged with both ruby-on-rails-4 and ruby-on-rails-3.2?Andrew Grimm

1 Answers

0
votes

The problem has nothing to do with your nested forms, it has to do with a not null constraint in your SQLite schema. Either pass in your client_id to validate the constraint or remove the constraint from the db