我有一个附有证人的事件。
我正在尝试显示从嵌套属性中删除附件的链接,但我的链接是拉取父记录(invoice.id)的id而不是嵌套/子记录(invoice.witness_id)。
我知道我在路线上做错了,或者从控制器或视图中拨打了正确的身份证号码......感谢任何帮助!
incident.rb
has_many :witnesses
accepts_nested_attributes_for :witnesses, :reject_if => :all_blank, :allow_destroy => true
witness.rb
belongs_to :incident
has_attached_file :statement
的routes.rb
match 'witness/:id' => 'witnesses#remove_statement', via: [:get, :post], as: 'remove_statement'
witnesses_controller
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 partial
<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 -->
.....
答案 0 :(得分: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。
请注意,由于您动态添加这些,因此对于新记录,这将无效(因为不知道)。
因此,您必须检查记录是否为new_record?
,并且只显示该链接(如果不是(因为那时您将拥有有效的ID)。如果它不是新记录,您可以使用cocoon助手将其删除。