Reputation: 2565
I don't know how to return checked values. There is my code
controller:
def index
// there I would like to get checked cities
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @cities }
end
end
viewer:
<%= render 'form' %>
_form:
<% for cities in Database.find(:all) %>
<div>
<%= check_box_tag cities.city1 %>
<%= cities.city1 %>
</div>
<% end %>
EDIT
I tried:
@cities = Database.find(:all)
params[:cities].each do |city|
...
end
and
<% for city in @cities %>
<%= check_box_tag "cities[]", city.id %> <%= city.city1 %>
<% end %>
but got error:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
Upvotes: 3
Views: 9201
Reputation: 8408
Hi Your problem seems to be similar to HABTM through checkboxes try
<%form_tag "some_action", :method => :post do %>
<% Database.find(:all).each do |city| %>
<div>
<%= check_box_tag "cities[]",city.city1, :false %>
<%= citiy.city1 %>
</div>
<% end %>
<%end%>
and inside controller
def some_action
if !request.post?
@cities = Database.find(:all)
render 'view'
else
params[:cities].each do |city|
...
end
redirect_to view_path
end
end
Upvotes: 5
Reputation: 8240
Put a debugger in your controller code. What happens when you inspect your params? Is there anything similar to params[:cities]? If so, what's in there?
Upvotes: 1
Reputation: 18100
To do this you'll want to iterate over the list of cities and add a check_box_tag with the name "cities[]" for each.
I usually provide the list as a variable to use in the view. Do the Database.find in the controller.
<% for city in @cities %>
<%= check_box_tag "cities[]", city.id %> <%= city.name %>
<% end %>
Note - if no checkboxes are checked, nothing will be submitted for the param - ie, there won't be a 'cities[]' param at all. You may need to add this depending on the logic of your search. If so, add to the form...
<%= hidden-field_tag "cities[]", '' %>
Or you can handle it in the controller.
Upvotes: 2