Reputation: 197
I recently asked a question about using some values in a hash for the labels of either radio buttons or check box in a rails form instead of hard coding in the label: Using elements of a Hash as radio Button. I tried to solve this by creating a helper method that takes in the hash(basically a table in my database) and maps the required parameter into an array but looping through the array; while using the parameters as a label hasn't produced the desired result, it outputs the value of iterator instead of outputting the result of the lines of code i wrote. Below is my helper method.
def sport_select(sport)
x = Sport.all.map {|e| e.sport_name}
for i in 1..x.length
check_box_tag(x[i], checked_value = 1, unchecked_value = 0)
end
end
The line x = Sport.all.map {|e| e.sport_name}
produces ["sport_name", "sport_name"]
; but the for loop only shows 1..2
. I have tried changing x = Sport.all.map {|e| e.sport_name}
to x = Sport.all.map {|e| [e.id, e.sport_name]}
to use it as a hash, which produces [[id, "sport_name"],[id, "sport_name"]]
but i have had issues using the id
as the key to the hash. Any help will be appreciated. Thanks.
Upvotes: 0
Views: 284
Reputation: 239290
This isn't sane:
check_box_tag(x[i], checked_value = 1, unchecked_value = 0)
The method definition is:
check_box_tag(name, value = "1", checked = false, options = {})
You're passing 1 for value
, and 0 for checked
. You cannot "name" parameters with variable = value
, all you're doing is setting a variable and then passing the same value through to the method.
If you want to produce a checkbox where the name is the sport's name and its value is the id of the sport, get rid of your pair of loops and just us a single loop:
def sport_select(sport)
Sport.all.map do |e|
check_box_tag(e.sport_name, e.id)
end
end
If you're outputting the result to a page, you will also probably want to use .join('').html_safe
to return a single string, and prevent it from being escaped.
Upvotes: 1
Reputation: 54882
This should display all the Sport records as radio buttons:
def sports_as_radio_buttons(sports = Sport.scoped)
html = "".html_safe
sports.each do |sport|
html += radio_button_tag('sport_id', sport.id, id: "sport_#{sport.id}")
html += label_tag("sport_#{sport.id}", sport.name)
end
html
end
Hope this helps!
Upvotes: 0