Absolutely stuck trying to create nested association in rails form with has_many through

前端 未结 1 940
南笙
南笙 2021-02-09 09:52

I posted an earlier question about this and was advised to read lots of relevant info. I have read it and tried implementing about 30 different solutions. None of which have wor

相关标签:
1条回答
  • Instead of calling:

    @production = @miniature.productions.create
    

    Try Rails' "build" method:

    def new
      @miniature = Miniature.new(miniature_params)
      @miniature.productions.build
    end
    
    def create
      @miniature = Miniature.new(miniature_params)
      if @miniature.save
        redirect_to @miniature
      else
        render 'new'
      end
    end
    

    Using the build method uses ActiveRecord's Autosave Association functionality.

    See http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

    You also need to update your params method, e.g.

    def miniature_params
      params.require(:miniature).permit(:name, :release_date, :material, :scale, productions_attributes: [:manufacturer_id])
    end
    

    Also your fields_for should be plural (I think)...

    <%= f.fields_for :productions do |production_fields| %>
    
    0 讨论(0)
提交回复
热议问题