【问题标题】:link to association not working in rails 4 using cocoon gem使用茧宝石链接到在 Rails 4 中不起作用的关联
【发布时间】:2019-01-21 09:29:22
【问题描述】:

我有一个与关联相关的课程模型和周模型。 Link_to_association 没有在点击时呈现任何表单,也没有生成日志来检查错误。

课程模型

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

周模型

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 %>

参数:

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

【问题讨论】:

  • 您是否将//= require cocoon 添加到application.js 文件中?或者如果有的话,为管理部分分离 js 清单?
  • 并尝试在 `

标签: ruby-on-rails associations nested-forms cocoon-gem


【解决方案1】:

经典错误:您将link_to_association 放在f.fields_for 循环内。这意味着只有在已经嵌套的元素可用时才会显示链接。

cocoon 文档中的示例是 haml,其中缩进很重要。如果对haml不熟悉,也可以查看ERB examples。因此,在您的情况下,您应该编写类似

的内容
  <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>

【讨论】:

    猜你喜欢
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多