首页 > 解决方案 > 检查复选框是否被选中 rails

问题描述

我正在尝试从头开始创建我的第一个 Rails 应用程序,但我认为我不应该为此使用 Rails。我有一个使用方法 make_calls 的按钮,在 make 调用中,我让它发出一堆由 sleep 语句分隔的不同调用,但是我只需要在选中 calls_check 复选框时执行这些调用。这是我所拥有的:
在我的控制器中:

# called from inside make_calls method
def individual_call(to_phone, xml_url)

call = @client.calls.create(
                           url: xml_url,
                           to: to_phone,
                           from: '+13474275841',
                           timeout: 20
                         )
if params[:calls_check] == '1'
    puts call.sid
end


在我看来:

<body>
    <div class="buttonDiv w3-display-middle">
         <%= check_box :calls_check, id: "calls_check" %>Make Calls
         <%= button_to "Start Call Sequence", action: "make_calls" %>
    </div>
</body>

但即使未选中该复选框,它仍在进行调用。有什么建议吗?

标签: ruby-on-railsrubycheckboxtwilio

解决方案


You should use check_box_tag Instead of check_box

Reason being check_box accepts 2nd parameters as a method (It’s intended that method returns an integer and if that integer is above zero, then the checkbox is checked)

Using check_box_tag

<%= check_box_tag :calls_check, 1, false %>

Which means that once checkbox will be checked it will send parameter as '1' and by default it will be unchecked, In case of unchecked it won't send parameter of calls_check(i.e params[:calls_check] = nil)

At controller side

# called from inside make_calls method
def individual_call(to_phone, xml_url)

call = @client.calls.create(
                           url: xml_url,
                           to: to_phone,
                           from: '+13474275841',
                           timeout: 20
                         ) if params[:calls_check].eql?('1')
    puts call.sid
end

Wrap check_box with form so that it send data on button click,

replace make_calls_path with the make_call action path and also its method get or post. according to your defined routes

<body>
  <div class="buttonDiv w3-display-middle">
    <%=form_tag make_calls_path, method: :get do %>
      <%= check_box_tag :calls_check, id: "calls_check" %>Make Calls
      <%= submit_tag "Start Call Sequence"%>
    <%end%>
  </div>
</body>

推荐阅读