views:

17

answers:

2

I have a method in my application helper that is meant to deactivate a task in my database.

Application helper:

  def link_to_destroy_task(task_id)
    Task.find(task_id).deactivate
  end

Model:

def self.deactivate()
  update_attribute(:active, false)
end

View:

<ol id="tasks">
  <% @Tasks.each do |task| %>
      <%content_tag_for :li, task do %>
      <span class ="handle"> [drag] </span>
      <%= link_to task.name, :controller => "com_tasks", :action => "edit", :id => task.id %>
      <%= link_to_function '[Delete]', link_to_destroy_task(task.id) %>
    <% end %>
  <% end  %>
</ol>

For some reason when the page loads it is deleting everything from the list. Not just switching active to false. It is completely wiping it from the database.

I am using fixtures, so I reload all the test data, and I can refresh once to see the data again, but the next time I reload it is gone.

I have changed the name of the method to 'deactivate' because I think destroy is already taken, but the method is still being run without being clicked. It isn't deleting anymore, but it is deactivating everything.

+1  A: 

Pay attention to this line

<%= link_to_function '[Delete]', link_to_destroy_task(task.id) %>

You're actually executing link_to_destroy_task function here, once for each task.

From the docs

def link_to_function(name, *args, &block)
Returns a link of the given +name+ that will trigger a JavaScript +function+ using the onclick handler and return false after the fact.

Never used this method, but it seems its purpose is to invoke JavaScript function, not Ruby function.
There're examples too.

Nikita Rybak
+1  A: 

This is happening because you're calling deactivate in your view for each item! The 2nd parameter to your link_to_function is running the actual deactivation.

I think you're misunderstanding link_to_function - it doesn't run a ruby function when clicked, it runs a javascript function you've created. The 2nd parameter needs to be a string that contains a javascript function. Rails would have no way to run a ruby method in somebody's browser.

Here's a link to the documentation, which should get you on the right track:

http://apidock.com/rails/ActionView/Helpers/JavaScriptHelper/link_to_function

Jaime Bellmyer
Ohk. I originally had it in the controller than i thought I was meant to move it to a helper. Is there a way to create a link to a action in the application controller? I wanted it to be available from different views from different controllers. And I didn't think replicating the code was a good idea
inKit