class Test < ApplicationRecord belongs_to :legal validates :legal, presence: true, allow_nil: true validates :ref, length: { minimum: 1 }, allow_nil: true end <div class="field"> <%= f.label :ref %> <%= f.collection_select :ref, Legal.all, :id, :name_s %> </div> <div class="field"> <%= f.label :ref1 %> <%= f.text_field :ref1 %> </div> <div class="field"> <%= f.label :value_s %> <%= f.text_field :value_s %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> 

It would seem banal, because the conservation request is obvious:

Parameters: {"utf8" => "✓", "authenticity_token" => "**************", "test" => {"ref" => "1", "ref1 "=>" 1212 "," value_s "=>" 23232 "}," commit "=>" Create Test "}

However, an error occurs

Legal must exist

while the legal table clearly has an entry with id = 1

    1 answer 1

    You have a legal field in the model, but there is no such field in the form, and it is not in the parameters. The only mention is Legal in the f.collection_select drop-down list, but the field is called ref . When you fill out and try to save the model, validation is triggered.

     validates :legal, presence: true, allow_nil: true 
    • does it mean I need to add a legal field to the form? how to do it? - ilyas July
    • @ilyasJuly And what is this field intended for? Is it somehow connected with the Legal model or is it another purpose? In general, yes, you need to either add a drop-down list for it, or place its hidden (hidden) field, or change the validation of this field in the model. - cheops
    • Yes, id must be stored in the ref field from the table legal - ilyas July
    • @ilyasJuly Do you have a legal_id field in your model (judging by the relationship belongs_to: legal)? If so, what value should it take? - cheops
    • A small clarification. legal is a relation, not a field. By the way, in 5 rails for belongs_to to required: true , so separate validation is not needed. - anoam