Override one attribute in strong Rails options

Is there a way to override one attribute but still use strong parameters in Rails? For example, in the following example, if I would like to override the username every time, but also use the person_params

. There must be a better way than manually installing @person.name

, right?

class PeopleController < ActionController::Base

  def create
    @person = Person.new(person_params)
    @person.name = "ABC"
    @person.save
  end

  private

    def person_params
      params.require(:person).permit(:name, :age)
    end
end

      

+3


source to share


2 answers


If all you want to do is override the name for some other string, or format it before saving, you can simply do:

@person = Person.new(person_params.merge!(name: 'ABC'))

      



If you want to do create and merge in one line, just do this:

def create
    @person = Person.create(person_params.merge!(name: 'ABC'))
end

      

+5


source


You can also do something similar to this: http://api.rubyonrails.org/classes/ActionController/Parameters.html

It looks like you would form a hash from the parameters you want. Link:



params = ActionController::Parameters.new({
  person: {
    name: 'Francesco',
    age:  22,
    role: 'admin'
  }
})

permitted = params.require(:person).permit(:name, :age)
permitted            # => {"name"=>"Francesco", "age"=>22}
permitted.class      # => ActionController::Parameters
permitted.permitted? # => true

Person.first.update!(permitted)
# => #<Person id: 1, name: "Francesco", age: 22, role: "user">

      

0


source







All Articles