Trouble with accepts_nested_attributes_for in Rails 5.0.0.beta3, -api option

后端 未结 5 1848
野性不改
野性不改 2021-01-04 19:28

I am using Rails 5.0.0.beta3, building an API-only app using the -app option on rails new, and I am having trouble with accepts_nested_attributes_for.

In my app, a

相关标签:
5条回答
  • 2021-01-04 19:39

    I had the same problem and I found the solution in https://github.com/rails/rails/issues/18233

    Just add

    class Post < ApplicationRecord
    belongs_to :member, required: false
    end
    

    It seems a problem with accepts_nested_attributes_for in Rails 5, so you need add required: false to your child models.

    0 讨论(0)
  • 2021-01-04 19:39

    I found that adding the inverse_of options to the associations allowed accepts_nested_attributes to work. Nice than monkey patching, still allows the association to be validated

    0 讨论(0)
  • 2021-01-04 19:46

    I am experiencing problems with accepts_nested_attributes_for as well in my Rails 5 beta 3 app and seems like it is buggy. Ideally, a bug report should be submitted, but we didn't have time to do it properly. We have the following setup:

    accepts_nested_attributes_for :attachments, allow_destroy: true
    

    Eventually, we had to monkey-patch the method inside the model like this:

      def attachments_attributes=(attributes)
        attributes.reject! do |_attachment|  
          if _attachment = Attachment.find(_attachment['id'])
            if _attachment.drop_id.nil?
              attachments << _attachment
              next true
            end
          end
          next false
        end
        # assign_nested_attributes_for_collection_association(:attachments, attributes)
      end
    

    The only thing is that the last (commented-out line) with assign_nested_attributes_for_collection_association has some issues, but hopefully this will provide you an idea how this can be fixed.

    0 讨论(0)
  • 2021-01-04 19:50

    This is a regression reported as rails#25198. As was pointed out, you may use inverse_of as a workaround.

    It is planned to be fixed in 5.0.1.

    0 讨论(0)
  • 2021-01-04 19:53

    I also encountered the same problem.
    It seems specification has been changed from Rails 5.
    By putting the option, and the previous and the same operation.

    belongs_to should default to required: true #18233

    class Post < ApplicationRecord
      belongs_to :member, optional: true
    end
    

    It is my clumsy may speak English, but ...

    0 讨论(0)
提交回复
热议问题