gpt4 book ai didi

ruby-on-rails-4 - 如何为 params.permit 设置默认值

转载 作者:行者123 更新时间:2023-12-05 00:41:29 24 4
gpt4 key购买 nike

我想为我允许的参数之一设置一个默认值。

我试着像他们说的那样做http://api.rubyonrails.org/classes/ActionController/Parameters.html

class UsersController < ApplicationController

def new
@user = User.new
end

def show
@user = current_user
end

def create
user_params = ActionController::Parameters.new({
user: {
avatar_link: '/assets/avatar-placeholder.png'
}
})
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to user_path(current_user)
else
redirect_to new_user_path
end
end

private

def user_params
params.require(:user).permit(:name, :username, :email, :password, :password_confirmation, :avatar_link)
end
end

但它似乎不起作用——我得到 ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError) 因为这部分:

user_params = ActionController::Parameters.new({
user: {
avatar_link: '/assets/avatar-placeholder.png'
}
})

我应该如何为我的 params 设置默认值?

UPD:我尝试使用 @xlembouras 解决方案,但现在我有 rollback transaction

def user_params
defaults = {avatar_link: '/assets/avatar-placeholder.png'}
params.require(:user).permit(:name, :username, :email, :password, :password_confirmation, :avatar_link).reverse_merge!(defaults)
puts params
end

models/user.rb

class User < ActiveRecord::Base
before_save { self.email = email.downcase }
has_secure_password
validates_confirmation_of :password
has_many :projects

validates :name, presence: true, length: {maximum: 50}
validates :username, presence: true, uniqueness: { case_sensitive: false }, length: {maximum: 50}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: {with: VALID_EMAIL_REGEX}, uniqueness: { case_sensitive: false }
validates :password, presence: true, length: {minimum: 6}
validates :password_confirmation, presence: true
end

最佳答案

您可以利用 permit 的输出可以作为哈希处理的事实,并且只需使用 reverse_merge

def create
user = User.new(user_params)
...
end

private

def user_params
defaults = { name: 'A name' }
params.require(:user).permit(:name, :username, :email,
:password, :password_confirmation,
:avatar_link).reverse_merge(defaults)
end

关于ruby-on-rails-4 - 如何为 params.permit 设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33573426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com