0

我有一个附带证人的事件。

我正在尝试显示一个链接以从嵌套属性中删除附件,但我的链接正在提取父记录 (invoice.id) 的 :id 而不是嵌套/子记录 (invoice.witness_id)。

我知道我在路由或从控制器或视图调用正确的 ID 号时做错了......任何帮助表示赞赏!

事件.rb

  has_many :witnesses
  accepts_nested_attributes_for :witnesses, :reject_if => :all_blank, :allow_destroy => true

见证人.rb

  belongs_to :incident  
  has_attached_file :statement

路线.rb

match 'witness/:id' => 'witnesses#remove_statement', via: [:get, :post], as: 'remove_statement'

见证人控制器

  def index
    @witnesses = @incident.witnesses.all
  end

  def remove_statement
    @witness = Witness.find(params[:id])
    @witness.statement = nil
    respond_to do |format|
        if @witness.save
          format.html { redirect_to :back, notice: 'Attachment was removed.' }
          format.json { head :no_content }
        else
          format.html { redirect_to :back, error: 'Attachment could not be removed.'  }
          format.json { render json: @witness.errors, status: :unprocessable_entity }
        end
    end
     end

  private
    def set_witness
      @witness = @incident.witnesses.find(params[:id])
    end

    def witness_params
      params[:witness].permit(:first_name, :last_name, :phone, :email, :statement, :incident_id)
    end

_witness_fields 部分

<div class="nested-fields">
  <div class="form-group">
    ....
    <%= link_to "Remove Attachment", remove_statement_path, :id => :witness_id  %>
    ...

事件/_form.html.erb

<%= form_for(@incident, html: { :multipart => true , class: 'form-horizontal' }) do |f| %>
  <%= f.error_notification %>

    <% if @incident.errors.any? %>
    <div class="red">
      <% @incident.errors.full_messages.each do |msg| %>
       <%= msg %><hr>
      <% end %>
    </div>
  <% end %>
.....

<!-- WITNESS SECTION -->
<div class="span6">
<hr>
    <fieldset id="witnesses">
        <%= f.fields_for :witnesses do |builder| %>
          <%= render 'witness_fields', :f => builder %>
        <% end %>    
    </fieldset>
    <p class="links">
      <%= link_to_add_association 'Add Witness/Contact', f, :witnesses, { class:"btn btn-primary" } %>
        </p>
    </div>
    </div>
    <!-- END WITNESSES SECTION -->
.....
4

1 回答 1

0

在你的_withness_fields部分,你写

<%= link_to "Remove Attachment", remove_statement_path, :id => :witness_id  %>

那应该是这样的

<%= link_to "Remove Attachment", remove_statement_path(f.object.id)  %>

所以有两件事:路径助手remove_statement_path需要id作为参数,其次,您需要实际给它当前正在渲染的对象的正确 id。

请注意,由于您动态添加这些,因此对于新记录,这将无效(因为不知道)。

因此,您必须检查记录是否为 a new_record?,如果不是,则仅显示该链接(因为您将拥有有效的 id)。如果它不是新记录,您可以使用 cocoon helper 将其删除。

于 2014-04-03T08:13:45.563 回答