Rails / nested attributes / file _field do not appear in options when empty

I have two models, the first ( model_1) accepts nested attributes for the second ( model_2). The second model has only one field ( file), which is referred to in the form as a file field.

The problem occurs when the file is not selected. In this case - except with a text field - the field does not appear at all in the POST parameters, for which the first model believes that no nested model should be created at all. Which cannot initiate checks, etc. If I were to add a second field to model_2 and the corresponding form, and if I use text input, everything will go through precise and natural checks that work just fine for the file field.

Does anyone have any experience on how to do this?

And for the best some (simplified) code - the form:

= form_for @model_1, :html => { :multipart => true } do |f|
    - # fields for model 1 …
    = f.fields_for :model_2 do |builder|
        - # if this is empty, it like no model_2 would be created at all:
        = builder.file_field :file

Model 1:

class Model1 < ActiveRecord::Base
    has_many :model_2s, :dependent => :destroy
    accepts_nested_attributes_for :model_2s
    # …
end

and Model 2:

class Model2 < ActiveRecord::Base
    belongs_to :model_1
    validates_presence:of :file
    # …
end
+3
source share
2 answers

I would suggest adding a check on your controller and returning the message [: error] if the file field is missing.

You can also manually add fields if they do not exist to activate validation:

m1params = params [: model_1]
m1params [: model_2_attributes] = {} unless m1params.has_key? (: model_2_attributes)

Finally, you can create a fake attribute in your Model_2 model, which you could use to ensure that model_2_attributes are passed in the form:

class Model2
  attr_writer: fake

  def fake
    @fake || = 'default'
  end
end

= form_for @ model_1,: html => {: multipart => true} do | f |
    - # fields for model 1 ...
    = f.fields_for :model_2 do |builder|
        = builder.hidden_field :fake
        = builder.file_field :file
+1

, , , :

https://github.com/perfectline/validates_existence

:

class Unicorn < ActiveRecord::Base
  belongs_to :wizard
  belongs_to :person, :polymorphic => true

  validates :wizard,    :existence => true
  validates :wizard_id, :existence => true # works both way
  validates :person,    :existence => { :allow_nil => true, :both => false }
end
0

Source: https://habr.com/ru/post/1790242/


All Articles