Penny
Penny

Reputation: 157

link to association not working in rails 4 using cocoon gem

I have a course model and week model which is connected with associations. Link_to_association is not rendering any form on clicked and there are no logs generated to check the error.

course model

class Course < ApplicationRecord
  belongs_to :startup
  belongs_to :program
  has_many :weeks
  accepts_nested_attributes_for :weeks,allow_destroy: true
end

week model

class Week < ApplicationRecord
  belongs_to :course
  has_many :events
  belongs_to :startup
end

_new.html.erb

 <%= form_for [:admin, @course] do |f| %>
  <%= f.label :name %> <br>
  <%= f.text_field :name, class: "input-md form-control mb-20" %><br> 
  <%= f.label :program_id, "Program" %> <br>
  <%= f.collection_select :program_id, Program.where('id'), :id, :name, {}, {class: "input-md form-control mb-20"} %>
  <%= f.label :duration %> <br>
  <%= f.text_field :duration, class: "input-md form-control mb-20" %>
  <%= f.fields_for :weeks, name: "weeks", id: 'weeks' do |week1| %>
     <%= render partial: 'week_fields', locals: {f: week1} %><br>
     <%= link_to_add_association 'Add more weeks', f, :weeks, class: "btn btn-mod btn-medium btn-round submit-button"%>
  <% end %>
  <%= f.submit :submit %>
<% end %>

params:

ActiveAdmin.register Course do
    permit_params :name, :duration, :startup_id, :program_id, weeks_attributes: [:id, :name, :description]
    form partial: "new"
    controller do
    def new
        @course = Course.new
        @course.weeks.build
    end
end

Upvotes: 0

Views: 502

Answers (1)

nathanvda
nathanvda

Reputation: 50057

Classic mistake: you place the link_to_association inside the f.fields_for loop. This means the link will only be shown if already nested elements are available.

The examples on the cocoon documentation are haml, where indentation is important. If you are not familiar with haml, you can also check the ERB examples. So in your case you should be writing something like

  <div id='weeks'>
    <%= f.simple_fields_for :weeks do |week| %>
      <%= render 'week_fields', :f => week %>
    <% end %>
    <div class='links'>
      <%= link_to_add_association 'add week', f, :weeks, class: "btn btn-mod btn-medium btn-round submit-button" %>
    </div>
  </div>

Upvotes: 1

Related Questions