Cocoon gem - 嵌套表单保存元素,请求新模板文件并显示空字段

时间:2018-02-03 11:55:06

标签: ruby-on-rails ruby-on-rails-5 cocoon-gem

我知道这个问题曾经无数次问过,但我找不到任何有问题的人。

值得注意的是,这是一种单一资源。

模型/ basic.rb

class Basic < ApplicationRecord
  has_many :social_networks
  accepts_nested_attributes_for :social_networks, reject_if: :all_blank, allow_destroy: true
  mount_uploader :logo, LogoUploader
end

模型/ social_network.rb

class SocialNetwork < ApplicationRecord
  belongs_to :basic
end

控制器/ basic_controller.rb

def show
end

def new
  @basic = Basic.new
  @basic.social_networks.build
end

def edit
end

private

# Use callbacks to share common setup or constraints between actions.
def set_basic
  @basic = Basic.first
end

# Never trust parameters from the scary internet, only allow the white 
list through.
def basic_params
  params.require(:basic).permit(:base_title, :resume, :logo, social_networks_attributes: [:id, :name, :url])
  end
end

视图/基础/ _form.html.erb

<%= form_with(model: @basic, local: true, url: basics_path) do |f| %>
  <div id="social_networks">
    <%= f.fields_for :social_networks do |sn| %>
      <%= render 'social_networks', f: sn %>
    <% end %>

    <div class="links">
      <%= link_to_add_association 'Ajouter', f, :social_networks %>
    </div>
  </div>
<%= end %>

_social_network_fields.html.erb

<div class="nested-fields">
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name, placeholder: 'Nom' %>
  </div>

  <div class="field">
    <%= f.label :url %>
    <%= f.text_field :url, placeholder: 'Lien' %>
  </div>

  <div class="links">
    <%= link_to_remove_association 'Supprimer', f %>
  </div>
</div>

如问题标题中所述,我的表单工作正常,并保存了我正确填写的元素。但是,当我想编辑时,我收到一条错误消息,说它无法找到资源的模板(它等待名为_social_networks.html.erb的文件)。当我添加它(并让它空白)时,我得到了表单,好像我想创建一些新资源。

我做错了什么?

提前谢谢

1 个答案:

答案 0 :(得分:3)

你写了

<%= render 'social_networks', f: sn %>

但您的观点是_social_networks_fields.html.erb

你能不能将_social_networks_fields.html.erb重命名为_social_networks.html.erb?

同时更改添加关联链接:

<div class="links">
  <%= link_to_add_association 'Ajouter', f, :social_networks, :partial => 'social_networks' %>
</div>

或者只是使用

<%= render 'social_networks_fields', f: sn %>

而且您不需要social_networks.html.erb