Rails checkbox change in db
I am total beginner in rails, trying to get some stuff together. I was browsing Stack Overflow about this issue for a while, but none of the advised stuff worked (and since I know Rails and Ruby are changing a lot - I guess it is normal).
So, the thing is - I want to create AJAX call when I click the checkbox, and later, change one boolean-type value in DB. My "object" is task and attribute is "status".
I tried:
<div class="header">
<% form_for @task, :id => "status" do |f| %>
<label><%= f.check_box :called, :onclick => "$('#status').submit()" %></label>
<% end %>
</div>
But it complains about undefined method model_name for NilClass:Class
.
Can you please maybe help with this?
Thank you very much.
EDIT:
Hmm, still that nasty error. Maybe the problem is in surroundings?
<% @tasks.each do |task| %>
<div class="post" id="<%= task.id =%>">
<div class="header"><%= form_for(@task, :id => "status", :remote => true) do |f| %>
<label>
<%= f.check_box :called %>
<%= f.su开发者_StackOverflow社区bmit %>
<% end %> <span class="title"><%= task.title =%></span>
</label>
The problem would seem to be that @task is nil. Perhaps copy and paste the controller code.
I would normally include a non-nil @task in both the "new" and "edit" actions
def new
@task = Task.new
end
def create
@task = Task.new(params[:task])
...
end
def edit
@task = Task.find(params[:id])
end
I'm guessing in this example @task is nil.
edit: adding a better way to do the form submit.
Also I would suggest not using the :on_click html attribute. in particular, this will not send an ajax submit.
I suggest you use the jquery rails helpers to make it sent via ajax. Namely add the :remote => true param to form_for
<% form_for(@task, :id => "status", :remote => true) do |f| %>
Also in Rails >3 you should use the <%=
for this type of tag.
<%= form_for(@task, :id => "status", :remote => true) do |f| %>
Lets rewrite it all
<%= form_for(@task, :id => "status", :remote => true) do |f| %>
<%= f.check_box :called %>
<%= f.submit %>
<% end %>
<script>
jQuery(function($){
// grab the form in this closure;
var form = $("form#status");
// hide the submit button
form.find("input[type=submit]").hide();
// set the click handler
$("#task_called").click(function(){
form.submit();
});
});
</script>
You should edit your question not post an answer with edits :)
Well, answer lies there:
1 <% @tasks.each do |task| %>
2 <div class="post" id="<%= task.id =%>">
3 <div class="header"><%= form_for(@task, :id => "status", :remote => true) do |f| %>
4 <label>
5 <%= f.check_box :called %>
Line 1 you loop @tasks
and create task
.
But line 3 you call @task
instead of task
精彩评论