Reputation: 4619
I have a controller:
class PortTestingController < ApplicationController
def index
@ports = {"80" => false, "443" => false, "2195" => true, "28009" => false}
end
end
This is what I have in my view:
- @ports.each_with_index do |(key,value), index|
- fields_for "ports[#{index}]", port do |f|
f.checkbox "#{key}" "#{key}"
=key
I've been looking at the documentation for a check_box:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box
and I have no idea what to put write for my checkbox. What's the method? What options can I pass in? What is checked value and unchecked value?
Upvotes: 1
Views: 330
Reputation: 2228
This is kind of a confusing aspect of ActionView
.
Since you are calling f.check_box
and not just simply check_box
(at least you will be once you fix your typo), the function you are actually calling is this one:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-check_box
However, the FormBuilder
method just passes the object represented by f
as the first parameter to a FormHelper
. So you can think of it like f.check_box ...
is equivalent to check_box f.object ...
The method
is the ActionView
attribute you want to set.
There are various options
that can be passed, but I find I generally just pass {}
The checked
value is what you want to pass if the checkbox is checked. By default it will be 1. Similarly, unchecked
passed by the form if the checkbox is unchecked. Sometimes I find that I want to reverse the polarity of a checkbox and I want to keep track of unchecked boxes, so I set checked
to 0 and unchecked
to 1.
Now to a more important point. All of these ActionView
methods are designed to work with ActiveRecord
models which you do not currently have. Your controller isn't setting @ports to a value derived from ActiveRecord::Base
. I think you should read up on that some more.
Upvotes: 1