Cannot build nested polymorphic associations'. Are you trying to build a polymorphic one-to-one association

浪尽此生 提交于 2019-12-12 03:53:24

问题


I have had a similar situation where i had Activities which has one Task which has one taskable and building the task would also build the taskable, like so:

def new
    @activity = Activity.new
    @activity.task = @activity.build_task
end

Now i have Terms which have many TermTranslations which have many attachments which have an attachable (Image or Audio) but line 18 @term = Term.new(permitted_params[:term]) of admin/term.rb i get this error:

Cannot build association `attachable'. Are you trying to build a polymorphic one-to-one association.

admin/term.rb

ActiveAdmin.register Term do
  permit_params :id, :display_name, :slug,
                term_translations_attributes: [:id, :slug, :title, :definition, :example, :language_id, :term_id, :_destroy,
                                               attachments_attributes: [:id, :name, :attachable_type, :attachable_id, :_destroy,
                                                                        attachable_attributes: [:id, :image_file, :audio_file, :_destroy]]]

  form partial: 'form'

  controller do
    def new
      @term = Term.new

      @term.term_translations.build.attachments.build
    end

    def create
      @term = Term.new(permitted_params[:term])

      @term.term_translations.each do |tt|
        tt.attachments.each do |a|
          a.attachable = create_attachable(permitted_params[:term][:term_translations_attributes])
        end
      end

      if @term.save
        redirect_to admin_term_path(@term)
      else
        render :new
      end

    end


    private

    def create_attachable(term_translations_params)
      raise term_translations_params.values[0].inspect
      attachable = term_translations_params.values[0][:attachments_attributes].values[0][:attachable_type].classify
      attachable.safe_constantize.new(term_translations_params.values[0][:attachable_attributes])
    end

  end
end

MODELS

class Term < ActiveRecord::Base
   has_many :term_translations, dependent: :destroy
   has_many :activities

   accepts_nested_attributes_for :term_translations, allow_destroy: true
end

-

class TermTranslation < ActiveRecord::Base
  belongs_to :language
  belongs_to :term
  has_many :attachments, dependent: :destroy

  accepts_nested_attributes_for :attachments, allow_destroy: true

  attr_accessor :attachable_attributes
end

-

class Attachment < ActiveRecord::Base
  belongs_to :term_translation
  belongs_to :attachable, polymorphic: true, dependent: :destroy

  accepts_nested_attributes_for :attachable, allow_destroy: true
end

-

class Image < ActiveRecord::Base
  has_attached_file :image_file, path: '/images/:filename'

  validates_attachment_content_type :image_file, content_type: /\Aimage\/.*\Z/

  has_one :attachment, as: :attachable
end

Views

admin/terms/_form.html.erb:

<%= semantic_form_for [:admin, @term], :builder => ActiveAdmin::FormBuilder, multipart: true do |f| %>

  <%= f.semantic_errors *f.object.errors.keys %>

  <%= f.inputs 'Details' do %>
    <%= f.input :display_name %>
    <%= f.input :slug %>
  <% end %>

  <%= render partial: '/admin/term_translations/form', locals: {f: f} %>

  <%= f.actions %>
<% end %>

admin/term_translations/_form.html.erb:

<% f.has_many :term_translations, heading: 'Translations', allow_destroy: true, new_record: true, multipart: true do |t| %>
    <% t.input :title %>
    <% t.input :slug %>
    <% t.input :language %>

    <% t.has_many :attachments, heading: 'Attachments', allow_destroy: true, new_record: true, multipart: true do |a| %>
        <% a.input :name %>

        <% if a.object.attachable %>
            <% a.input :attachable_type, as: :string, :input_html => { readonly: true } %>
        <% else %>
            <% a.input :attachable_type, as: :select, collection: ['Image', 'Audio'] %>
        <% end %>

        <div id='attachable_partial_container'>
          <% if a.object.attachable.class.to_s == 'Image' %>
              <%= render partial: '/admin/images/form', locals: { a: a } %>
          <% elsif a.object.attachable.class.to_s == 'Audio' %>
              <%= render partial: '/admin/audios/form', locals: { a: a } %>
          <% end %>
        </div>

        <script type="text/javascript">
            $(function () {
                $('#term_term_translations_attributes_NEW_TERM_TRANSLATION_RECORD_attachments_attributes_NEW_ATTACHMENT_RECORD_attachable_type_input').change(onTypeSelected);

                function onTypeSelected(e) {
                    if (e.val === 'Image')
                        $('#attachable_partial_container').replaceWith(renderImage());
                    else if (e.val === 'Audio')
                        $('#attachable_partial_container').replaceWith(renderAudio());
                }

                function renderImage() {
                    return (
                        "<div id='attachable_partial_container'>" +
                        "<%= escape_javascript render partial: '/admin/images/form', locals: {a: a} %>" +
                        "</div"
                    );
                }

                function renderAudio() {
                    return (
                        "<div id='attachable_partial_container'>" +
                        "<%= escape_javascript render partial: '/admin/audios/form', locals: {a: a} %>" +
                        "</div"
                    );
                }
            });
        </script>
    <% end %>
<% end %>

admin/images/_form.html.erb:

<%= a.inputs for: [:attachable_attributes, a.object.attachable || Image.new], multipart: true do |i| %>
    <% i.input :image_file, as: :file, multipart: true %>
<% end %>

admin/audios/_form.html.erb:

<%= a.inputs for: [:attachable_attributes, a.object.attachable || Audio.new], multipart: true do |i| %>
    <% i.input :audio_file, as: :file, multipart: true %>
<% end %>

Stack Trace

activerecord (4.2.0) lib/active_record/nested_attributes.rb:400:in `assign_nested_attributes_for_one_to_one_association'
    activerecord (4.2.0) lib/active_record/nested_attributes.rb:343:in `attachable_attributes='
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:54:in `public_send'
           activerecord (4.2.0) lib/active_record/attribute_assignment.rb:54:in `_assign_attribute'
    activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `block in assign_nested_parameter_attributes'
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `each'
           activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `assign_nested_parameter_attributes'
    activerecord (4.2.0) lib/active_record/attribute_assignment.rb:45:in `assign_attributes'
activerecord (4.2.0) lib/active_record/core.rb:557:in `init_attributes'
           activerecord (4.2.0) lib/active_record/core.rb:280:in `initialize'
    activerecord (4.2.0) lib/active_record/inheritance.rb:61:in `new'
activerecord (4.2.0) lib/active_record/inheritance.rb:61:in `new'
           activerecord (4.2.0) lib/active_record/reflection.rb:131:in `build_association'
    activerecord (4.2.0) lib/active_record/associations/association.rb:247:in `build_record'
activerecord (4.2.0) lib/active_record/associations/collection_association.rb:136:in `build'
           activerecord (4.2.0) lib/active_record/nested_attributes.rb:465:in `block in assign_nested_attributes_for_collection_association'
    activerecord (4.2.0) lib/active_record/nested_attributes.rb:460:in `each'
activerecord (4.2.0) lib/active_record/nested_attributes.rb:460:in `assign_nested_attributes_for_collection_association'
           activerecord (4.2.0) lib/active_record/nested_attributes.rb:343:in `attachments_attributes='
    activerecord (4.2.0) lib/active_record/attribute_assignment.rb:54:in `public_send'
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:54:in `_assign_attribute'
           activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `block in assign_nested_parameter_attributes'
    activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `each'
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `assign_nested_parameter_attributes'
           activerecord (4.2.0) lib/active_record/attribute_assignment.rb:45:in `assign_attributes'
    activerecord (4.2.0) lib/active_record/core.rb:557:in `init_attributes'
activerecord (4.2.0) lib/active_record/core.rb:280:in `initialize'
           activerecord (4.2.0) lib/active_record/inheritance.rb:61:in `new'
    activerecord (4.2.0) lib/active_record/inheritance.rb:61:in `new'
activerecord (4.2.0) lib/active_record/reflection.rb:131:in `build_association'
           activerecord (4.2.0) lib/active_record/associations/association.rb:247:in `build_record'
    activerecord (4.2.0) lib/active_record/associations/collection_association.rb:136:in `build'
activerecord (4.2.0) lib/active_record/nested_attributes.rb:465:in `block in assign_nested_attributes_for_collection_association'
           activerecord (4.2.0) lib/active_record/nested_attributes.rb:460:in `each'
    activerecord (4.2.0) lib/active_record/nested_attributes.rb:460:in `assign_nested_attributes_for_collection_association'
activerecord (4.2.0) lib/active_record/nested_attributes.rb:343:in `term_translations_attributes='
           activerecord (4.2.0) lib/active_record/attribute_assignment.rb:54:in `public_send'
    activerecord (4.2.0) lib/active_record/attribute_assignment.rb:54:in `_assign_attribute'
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `block in assign_nested_parameter_attributes'
           activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `each'
    activerecord (4.2.0) lib/active_record/attribute_assignment.rb:65:in `assign_nested_parameter_attributes'
activerecord (4.2.0) lib/active_record/attribute_assignment.rb:45:in `assign_attributes'
           activerecord (4.2.0) lib/active_record/core.rb:557:in `init_attributes'
    activerecord (4.2.0) lib/active_record/core.rb:280:in `initialize'
activerecord (4.2.0) lib/active_record/inheritance.rb:61:in `new'
           activerecord (4.2.0) lib/active_record/inheritance.rb:61:in `new'
    app/admin/term.rb:18:in `create'
actionpack (4.2.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
           actionpack (4.2.0) lib/abstract_controller/base.rb:198:in `process_action'
    actionpack (4.2.0) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (4.2.0) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
           activesupport (4.2.0) lib/active_support/callbacks.rb:117:in `call'
    activesupport (4.2.0) lib/active_support/callbacks.rb:151:in `block in halting_and_conditional'
activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
           activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
    activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
activesupport (4.2.0) lib/active_support/callbacks.rb:234:in `block in halting'
           activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
    activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
activesupport (4.2.0) lib/active_support/callbacks.rb:92:in `_run_callbacks'
           activesupport (4.2.0) lib/active_support/callbacks.rb:734:in `_run_process_action_callbacks'
    activesupport (4.2.0) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (4.2.0) lib/abstract_controller/callbacks.rb:19:in `process_action'
           actionpack (4.2.0) lib/action_controller/metal/rescue.rb:29:in `process_action'
    actionpack (4.2.0) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
activesupport (4.2.0) lib/active_support/notifications.rb:164:in `block in instrument'
           activesupport (4.2.0) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
    activesupport (4.2.0) lib/active_support/notifications.rb:164:in `instrument'
actionpack (4.2.0) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
           actionpack (4.2.0) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
    activerecord (4.2.0) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (4.2.0) lib/abstract_controller/base.rb:137:in `process'
           actionview (4.2.0) lib/action_view/rendering.rb:30:in `process'
    actionpack (4.2.0) lib/action_controller/metal.rb:195:in `dispatch'
actionpack (4.2.0) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
           actionpack (4.2.0) lib/action_controller/metal.rb:236:in `block in action'
    actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:42:in `serve'
           actionpack (4.2.0) lib/action_dispatch/journey/router.rb:43:in `block in serve'
    actionpack (4.2.0) lib/action_dispatch/journey/router.rb:30:in `each'
actionpack (4.2.0) lib/action_dispatch/journey/router.rb:30:in `serve'
           actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:802:in `call'
    warden (1.2.7) lib/warden/manager.rb:36:in `block in call'
warden (1.2.7) lib/warden/manager.rb:35:in `catch'
           warden (1.2.7) lib/warden/manager.rb:35:in `call'
    rack (1.6.8) lib/rack/etag.rb:24:in `call'
rack (1.6.8) lib/rack/conditionalget.rb:38:in `call'
           rack (1.6.8) lib/rack/head.rb:13:in `call'
    actionpack (4.2.0) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/flash.rb:260:in `call'
           rack (1.6.8) lib/rack/session/abstract/id.rb:225:in `context'
    rack (1.6.8) lib/rack/session/abstract/id.rb:220:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/cookies.rb:560:in `call'
           activerecord (4.2.0) lib/active_record/query_cache.rb:36:in `call'
    activerecord (4.2.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:647:in `call'
activerecord (4.2.0) lib/active_record/migration.rb:378:in `call'
           actionpack (4.2.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
    activesupport (4.2.0) lib/active_support/callbacks.rb:88:in `_run_callbacks'
activesupport (4.2.0) lib/active_support/callbacks.rb:734:in `_run_call_callbacks'
           activesupport (4.2.0) lib/active_support/callbacks.rb:81:in `run_callbacks'
    actionpack (4.2.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/reloader.rb:73:in `call'
           actionpack (4.2.0) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
    actionpack (4.2.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'
           web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'
    web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
           railties (4.2.0) lib/rails/rack/logger.rb:38:in `call_app'
    railties (4.2.0) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.2.0) lib/active_support/tagged_logging.rb:68:in `block in tagged'
           activesupport (4.2.0) lib/active_support/tagged_logging.rb:26:in `tagged'
    activesupport (4.2.0) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.2.0) lib/rails/rack/logger.rb:20:in `call'
           actionpack (4.2.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
    rack (1.6.8) lib/rack/methodoverride.rb:22:in `call'
rack (1.6.8) lib/rack/runtime.rb:18:in `call'
           activesupport (4.2.0) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
    rack (1.6.8) lib/rack/lock.rb:17:in `call'
actionpack (4.2.0) lib/action_dispatch/middleware/static.rb:113:in `call'
           rack (1.6.8) lib/rack/sendfile.rb:113:in `call'
    railties (4.2.0) lib/rails/engine.rb:518:in `call'
railties (4.2.0) lib/rails/application.rb:164:in `call'
           rack (1.6.8) lib/rack/lock.rb:17:in `call'
    rack (1.6.8) lib/rack/content_length.rb:15:in `call'
rack (1.6.8) lib/rack/handler/webrick.rb:88:in `service'
           /Users/lancecoe/.rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service'
    /Users/lancecoe/.rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run'
/Users/lancecoe/.rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/webrick/server.rb:296:in `block in start_thread'
           Request

           Parameters:

               {"utf8"=>"✓",
                "authenticity_token"=>"zehGpEWIuaFoAbIcOiDiaRiP7UAZxl999YuF79fPL9yypz55Jvo/QVEi3N6idELDTElORw2OoQMu3+2+CI63Pw==",
                "term"=>{"display_name"=>"angle",
                         "slug"=>"angle",
                         "term_translations_attributes"=>{"0"=>{"title"=>"angle",
                                                                "slug"=>"angle",
                                                                "language_id"=>"1",
                                                                "attachments_attributes"=>{"0"=>{"name"=>"sss",
                                                                                                 "attachable_type"=>"Image",
                                                                                                 "attachable_attributes"=>{"image_file"=>#<ActionDispatch::Http::UploadedFile:0x007feaadf23358 @tempfile=#<Tempfile:/var/folders/xc/wjddz4j93hl7pl9d3z6ks5340000gn/T/RackMultipart20170619-14398-1ihr5sn.png>,
                                                                                                                               @original_filename="Screen Shot 2017-06-19 at 5.06.39 PM.png",
                                                                                                                           @content_type="image/png",
                                                                                                                           @headers="Content-Disposition: form-data; name=\"term[term_translations_attributes][0][attachments_attributes][0][attachable_attributes][image_file]\"; filename=\"Screen Shot 2017-06-19 at 5.06.39 PM.png\"\r\nContent-Type: image/png\r\n">}}}}}},
                "commit"=>"Create Term"}

回答1:


Just had to add this to the Attachment model

  def build_attachable(params)
    self.attachable = attachable_type.constantize.new(params)
  end


来源:https://stackoverflow.com/questions/45295202/cannot-build-nested-polymorphic-associations-are-you-trying-to-build-a-polymor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!