How to Fix Forbidden Attributes Error in Ruby on Rails
forbidden attributes error in Ruby on Rails happens when you try to assign parameters without permitting them first. To fix it, use params.require(...).permit(...) in your controller to whitelist allowed attributes before saving or updating records.Why This Happens
This error occurs because Rails protects your app from unwanted or dangerous data by requiring you to explicitly allow which parameters can be used for mass assignment. If you try to save or update a model with parameters that are not permitted, Rails raises a ActiveModel::ForbiddenAttributesError.
def create
@user = User.new(params[:user])
@user.save
endThe Fix
To fix this, you need to use strong parameters by calling params.require(:model_name).permit(:attribute1, :attribute2). This tells Rails exactly which attributes are safe to use. Then pass the permitted parameters to your model.
def user_params params.require(:user).permit(:name, :email, :password) end def create @user = User.new(user_params) if @user.save redirect_to @user else render :new end end
Prevention
Always use strong parameters in your controllers to whitelist attributes before using them in mass assignment. Avoid passing params[:model] directly to model methods. Use Rails generators which scaffold strong parameters automatically. Consider adding tests to check parameter permissions.
Related Errors
Other common errors include Unpermitted parameters warnings when extra parameters are sent but not permitted, and Missing required parameter errors if you forget to use require. Fix these by carefully managing your strong parameters.
Key Takeaways
require and permit to avoid forbidden attributes errors.params[:model] directly to model methods like new or update.