Rails checkbox

I do not 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 an 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
+3
source share
3 answers

Hi Your problem seems to be similar to HABTM with try flags

<%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 the 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
+5
source

To do this, you will want to iterate over the list of cities and add check_box_tag named "cities []" for each.

I usually provide a list as a variable used in a view. Make Database.find in the controller.

<% for city in @cities %>
  <%= check_box_tag "cities[]", city.id %> <%= city.name %>
<% end %>

. , , .. "cities []". , . , ...

<%= hidden-field_tag "cities[]", '' %>

.

+2

Put a debugger in your controller code. What happens when you check your settings? Is there something similar to the parameters [: cities]? If so, what is there?

+1
source

Source: https://habr.com/ru/post/1779180/


All Articles