You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:实现Ruby on Rails按钮触发active布尔字段状态切换功能

Hey there! Let's get that toggle button working smoothly for your active boolean field. Your current code works, but we can clean up the duplicated form logic and make sure the button behaves exactly as you need—switching text and updating the active value with each click.

Simplified Toggle Form

Instead of repeating the entire form_for block twice, we can dynamically adjust the button text and submitted value based on the current state of case.active?. Here's the streamlined version:

<%= form_for @case do |f| %>
  <!-- Hidden field to send the opposite of the current active state -->
  <%= f.hidden_field :active, value: !@case.active? %>
  
  <!-- Dynamic button text that matches the action -->
  <%= f.submit @case.active? ? 'Unblock' : 'Block' %>
<% end %>

How This Works

  • We use a hidden_field to pass the opposite value of the current active state. So when the case is active (true), clicking the button sends false to mark it blocked. When it's inactive (false), clicking sends true to unblock it.
  • The submit button text updates automatically: if the case is active, the button says "Unblock"; if it's blocked, it says "Block".

Controller Setup

Make sure your cases_controller.rb has an update action that accepts the active parameter. This ensures the form submission actually updates the database:

def update
  @case = Case.find(params[:id])
  
  if @case.update(case_params)
    redirect_to @case, notice: 'Case status updated successfully.'
  else
    render :edit
  end
end

private

def case_params
  # Add any other fields you need to permit here
  params.require(:case).permit(:active)
end

Optional: Show Current Status

If you want to display the current state to users alongside the button, add this line inside the form:

<p>Current Status: <%= @case.active? ? 'Unblocked' : 'Blocked' %></p>

Quick Checks

  • Double-check that your Case model has the active boolean column set up with a default value of true (as you mentioned).
  • Confirm your routes are configured with resources :cases so form_for @case uses the correct update route automatically.

内容的提问来源于stack exchange,提问作者Harini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:11:10