开发者

rails: data being deleted on page reload

开发者 https://www.devze.com 2023-01-20 17:31 出处:网络
I have a method in my application helper that is meant to deactivate a task in my database. Application helper:

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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消