HUSTEN
HUSTEN

Reputation: 5197

Is that possible to add destroy action into _form.html.erb instead of index.html.erb

If I do scaffold, it automatically makes destroy action in index.html.erb.
What if I want to move this action to _form.html.erb?
And I'd like to make it appear only during edit mode(example.com/books/1212/edit)
not during new mode(example.com/books/new)

Upvotes: 1

Views: 142

Answers (2)

sameera207
sameera207

Reputation: 16629

This is possible, but make sure when you click on the delete button it does not file the form submit action.

You might consider using :remote => true for delete link and you could check if the record is new or existing by using:

<Object>.new_record?

Ex: if I have a model called Job

Job.first.new_record? #=> false

Job.new.new_record?   #=> true

Ex: something like (not tested :D, just to give you an idea)

<%= form_for(@job) do |f| %>
  #your form content
  <%= f.submit %>
  <%= (link_to 'Destroy', @job, :remote => true, method: :delete, data: { confirm: 'Are you sure?' }) unless @job.new_record? %>
<% end %>

Upvotes: 0

sameera207
sameera207

Reputation: 16629

I think this would help you

model

class Job < ActiveRecord::Base
  attr_accessible :delete_flag #with other attributes
  attr_accessor :delete_flag
end

*in your view (_form)*

<%= form_for(@job) do |f| %>
  #other code
  <%= f.text_field :delete_flag%>
  <div class="actions">
    <%= f.submit %>
    <%= f.submit "Delete",{:class => "delete_button"} %>
  </div>
<% end %>

coffeescript

jQuery ->
  $('#new_job').submit -> 
    #capture your delete button click
    $('#job_delete_flag').val("1")

in your controller you will get params as :delete_flag, and from there you could

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"5oWQU+w0jVCQlw8wLvCyKajbBSKpK2sv6RMkSGTE2H8=", "job"=>{"delete_flag"=>"1"}, "commit"=>"Delete"}

HTH

Upvotes: 1

Related Questions