如何为params.permit设置默认值

时间:2015-11-06 18:35:55

标签: ruby-on-rails-4

我想为我的一个授权参数设置一个默认值。

我试着像他们说的那样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

模型/ 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

1 个答案:

答案 0 :(得分:3)

您可以利用以下事实: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