Invalid association. Make sure that accepts_nested

2019-09-06 05:24发布

问题:

The error refers to

f.link_to_add

... line. When I remove that line, it works fine. But then I can't add more images.

<%= nested_form_for(:mark, url: place_mark_path, validate: true, html: {multipart: true}, 'data-update-target' => 'marks', class: 'marks') do |f| %>

  ...

  <%= f.text_field :title %>
  <%= f.check_box :mark %>

  <%= f.fields_for :mark_images do |p| %>
    <%= p.file_field :image %>
    <%= p.link_to_remove %><br>
  <% end %>

  <%= f.link_to_add "+ Add another image", :mark_images %>   <------ Problem

  <%= f.submit " Submit" %>

<% end %>

routes

  resources :places do
    resources :marks
  end

marks_controller

def new
    query = @factual.table('places')
    @place = query.filters('factual_id' => params[:place_id]).first
    @mark = Mark.new
    @mark.mark_images.build
end

mark model

  has_many :mark_images, :as => :attachable, :dependent => :destroy
  accepts_nested_attributes_for :mark_images

mark_images model

  belongs_to :attachable, polymorphic: true
  mount_uploader :image, ImageUploader 

回答1:

Changing this line

<%= nested_form_for(:mark, url: place_mark_path, validate: true, html: {multipart: true}, 'data-update-target' => 'marks', class: 'marks') do |f| %>

to this should work

<%= nested_form_for(@mark, url: place_mark_path, validate: true, html: {multipart: true}, 'data-update-target' => 'marks', class: 'marks') do |f| %>