I’ve just started programming in rails 3 days ago, learned ruby by the same time, and I’m having a hard time since yesterday figuring how to with one form, delete/update some of my instances, I only use one model “Task”. Here’s the code:
<%= form_for @task do |f| %>
<ul>
<% @tasks.each do |task| %>
<li id="task"><%= f.check_box :done %> <%= f.label :name %> </li>
<% end %>
<button onclick="doUpdate()">Mark Selected as done </button>
<%= button_to "Delete selected", :method => :delete %>
</ul>
<% end %>
Here’s the controller:
def delete
@tasks = Task.find(:all, :conditions => ["task.done = ?", true])
@tasks.each do |task|
task.delete
end
@tasks = Task.all
end
My model have only 2 parameters. name:String and done:Boolean, I wan’t to delete all the selected checkboxes. But this don’t work for me
Thanks in advance.
The problem is, you are doing it wrong(and I’ll tell you why). I could paste the code that would make it work but I’d rather explain, as you are probably doing it to learn.
Task.find(:all, :conditions => ["done = ?", true])will return EVERYTHING in your database where done = true. You will be erasing everything that is marked as done in the DATABASE, not what were marked on the form.Taskis your model, you can access the database by using find, where and other methods from activerecord(if activerecord doesn’t sound natural to you, activerecord lets you get stuff from the database without the need of writing SQL queries).What you really need to do in your controller is:
– You have to get what was sent from the form (check the documentation/web resources for the usage of
param[]).– For every checkbox marked true, you erase a record. (you got the each part right, this is good!)
I don’t think your view is right, I advise you to first be sure that the data that you receive is right(the params[]), then proceed to try to erase the record, or do whatever you want to do with it.
To “test” if your variables and code that is inside your controllers and models, use print @variable or something else(check rails docs how to debug).
I advise you use destroy instead of delete as other fellow stackoverflowers have said. Read the docs of destroy and delete.
Keep going 🙂