求助:实现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_fieldto pass the opposite value of the currentactivestate. So when the case is active (true), clicking the button sendsfalseto mark it blocked. When it's inactive (false), clicking sendstrueto 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
Casemodel has theactiveboolean column set up with a default value oftrue(as you mentioned). - Confirm your routes are configured with
resources :casessoform_for @caseuses the correct update route automatically.
内容的提问来源于stack exchange,提问作者Harini

