Rails:form_for复选框设置为true或false,无论该框是否被选中/取消选中 [英] Rails: form_for checkbox set to true or false whether the box is checked/unchecked
问题描述
我有一个叫做user的模型,它有2个布尔属性 send_email
和 send_text
。我有一个表单来编辑用户模型,我希望它根据框是否选中/取消选中,将这些属性设置为true / false。这是我的表格
I have a model called users that has 2 boolean attributes send_email
and send_text
. I have a form that edits the User model, and I want it to set those attributes to true/false depending on whether the box is check/unchecked. Here is my form
<%= form_for(@user) do |f| %>
<div class="field">
<%= f.label :email %> <br />
<%= f.text_area :email %> <br />
</div>
<div class="field">
<%= f.label :cell %> <br />
<%= f.text_area :cell %> <br />
</div>
<div class="field">
<%= f.label "Get Email" %> <br />
<%= f.check_box :send_email, {}, true, false %> <br />
</div>
<div class="field">
<%= f.label "Get Text" %> <br />
<%= f.check_box :send_text, {}, true, false %> <br />
</div>
<div class="actions">
<%= f.submit "Submit", class: "button small radius" %>
<%= link_to "go back", @user, class: "button small radius secondary" %>
</div>
<% end %>
这里是更新
动作 user_controller
def update
@user = User.find(params[:id])
@user.update_attributes(params[:user])
redirect_to @user
end
表单和更新看起来像完美,但是当我提交这个表单时,send_email或send_text框被选中,它不会改变用户模型的属性(send_email, send_text)为false
The form and update looks like it works perfectly, but when i submit this form with the send_email or send_text box checked, it does not change the attributes of the user model (send_email,send_text) to false
推荐答案
当您的表单正在处理某个对象时,Rails将为您执行此操作,只留下所有额外的东西关闭标签,如下所示:
Rails will do this for you when your form is acting on an object, just leave all the extra stuff off the tag like so:
<div class="field">
<%= f.label "Get Email" %> <br />
<%= f.check_box :send_email %> <br />
</div>
它应该都可以像你期望的那样开始工作。如果该属性为true,则勾选复选框,反之亦然,当您提交表单时,选中的状态将影响该属性。其余的代码没问题。
And it should all start working as you expect. The checkboxes will be ticked if the attribute is true, and vice versa the checked state when you submit the form will affect the attribute. Rest of your code is fine.
这篇关于Rails:form_for复选框设置为true或false,无论该框是否被选中/取消选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!