Ruby on Rails初级开发者求助:Simple Form下monthly repeats字段整数模型验证
Hey there! Let's get this sorted out for you. As a fellow Rails dev who's definitely made similar scaffold mishaps before, I know how frustrating this can be. Let's fix your monthly_repeats field to ensure it's always an integer—we'll cover database changes, model validations, and even tweak your Simple Form setup to match.
First things first: if you generated the scaffold with the wrong column type (like string), we need to update the database. Run this command in your terminal to create a migration:
rails generate migration ChangeMonthlyRepeatsToIntegerIn[YourTableName]
Replace [YourTableName] with the actual name of your table (e.g., ChangeMonthlyRepeatsToIntegerInTasks if your model is Task).
Next, open the generated migration file (in db/migrate/) and update it to look like this:
class ChangeMonthlyRepeatsToIntegerInYourTableName < ActiveRecord::Migration[7.0] def change # Add default: 0 and null: false if you want to avoid nil values change_column :your_table_name, :monthly_repeats, :integer, default: 0, null: false end end
Don't forget to replace your_table_name with your actual table name here. Then run the migration to apply the change:
rails db:migrate
Even if the database is fixed, we want to catch invalid inputs before they hit the database. Open your model file (e.g., app/models/task.rb) and add these validations:
class YourModel < ApplicationRecord # Your existing associations/validations go here # Ensure monthly_repeats is present, an integer, and non-negative (adjust as needed) validates :monthly_repeats, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } end
presence: truemakes sure the field isn't left blankonly_integer: truerejects any non-integer values (like strings or decimals)greater_than_or_equal_to: 0is optional—if your use case allows negative numbers, remove this or adjust it (e.g.,greater_than: -10if that makes sense for you).
Simple Form usually picks up on model column types, but just to be safe, let's explicitly set the input type in your form partial (e.g., app/views/tasks/_form.html.erb):
<%= simple_form_for @your_model do |f| %> <!-- Your other form fields here --> <%= f.input :monthly_repeats, as: :integer, input_html: { min: 0 } %> <%= f.button :submit %> <% end %>
Using as: :integer tells Simple Form to render a number input instead of a text box, and min: 0 adds a frontend constraint to prevent users from entering negative numbers (though remember, model validations are the real safety net here—frontend checks can be bypassed).
That's it! With these changes, your monthly_repeats field will be enforced as an integer at every level: database, model, and form.
内容的提问来源于stack exchange,提问作者Ben Strachan

