简体   繁体   中英

Can't get checkbox to behave with conditional statement in Ruby

Thanks in advance for your help! I'm giving my users a way of viewing information that they have saved in my MySQL database. The problem is that my checkbox state is not loading according to what the user saved in the record.

    <% if !params[:newitem_id].blank? and @newitem.optimize != 1 %>
    <input type="checkbox" name="optimize" id="optimize">
    <% else %>
    <input type="checkbox" name="optimize" id="optimize" checked="true">
    <% end %>

My conditional statement starts by looking to to see if there is a newitem_id. This is a hidden field, and it just connects up all of the @newitem information with the view.

    <input name="newitem_id" type="hidden" value="<%= params[:newitemid] %>" />  

When I use this in conditional statements elsewhere on the page, this works fine.

Next, my conditional statement looks into the record of @newitem to see whether optimize is a 1 or a 0. If @newitem.optimize is a 1, I want the checkbox checked. If not, I do not want it checked.

Unfortunately, the checkbox shows as checked even when the field is a 0.

EDIT 1

newitemlookup.html.erb is the view where the form with the checkbox lives. I've made some changes to it and have added the code from my controller. However, all of my checkboxes are checked, even if they are not supposed to be.

I also wanted to see what value the "@newitem.optimize" is returning, and it turns out that the 1 and the 0 in the database shows up in the view as "true" and "false" when I do <%= @newsavedmap.optimize %>. Could this be the problem?

newitemlookup_controller

    if params[:newitemid]
    @newitem = Newitem.find(:first, :conditions => {:id => params[:newitemid]})

newitemlookup.html.erb

    <% if params[:newitemid] and @newitem.optimize = false %>
    <input type="checkbox" name="optimize" id="optimize">
    <% else %>
    <input type="checkbox" name="optimize" id="optimize" checked="true">
    <% end %>

I did some research and figured out how to add a checkbox that would look at the record and then return the result. Here's the code I used. This replaced the if/then statement.

    <%= check_box_tag 'optimize', '1', @newitem.optimize %>

例如,如果您使用诸如f之类的表单构建器:

 <%= check_box_tag 'optimize', '1', f.object.optimize %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM