#actioncontrollerparameters
Explore tagged Tumblr posts
Text
New Post has been published on Ruby on Rails Tuts
New Post has been published on http://www.rortuts.com/ruby-on-rails/rails5-actioncontrollerparameters/
Rails 5: ActionController::Parameters
Rails 5: ActionController::Parameters Now Returns an Object Instead of a Hash.
Lot’s of people got confused. What was that?
So here is a small presentation which will quickly dive into it.
rails 4
raw_parameters = :name => 'rockers',:teams => :team1 => "37" parameters = ActionController::Parameters.new(raw_parameters) parameters # => "name"=>"rockers", "teams"=>"tet", "city"=>"Los Angeles" parameters.to_h # => "teams"=>"team1"=>"37" parameters.slice(:name,:city).to_h # => "name"=>"rockers", "city"=>"Los Angeles" parameters.to_unsafe_h.slice(:name, :city)
Rails 5
raw_parameters = :name => 'rockers',:teams => :team1 => "37",:city => 'delhi' parameters = ActionController::Parameters.new(raw_parameters) parameters # => <ActionController::Parameters "name"=>"rockers", "teams"=>"team1"=>"37" permitted: false> parameters.to_h # => parameters.slice(:name,:city).to_h # => Calling #to_h on this would return an empty hash because name and city aren’t permitted. parameters.to_unsafe_h.slice(:name, :city) # => "name"=>"et", "city"=>"Los Angeles"
Note1: By default controller and action parameters are allowed. To explicitly always allow other parameters you can set a configuration option in your application.rb config.always_permitted_parameters = %w( controller action param_1 param_2 )
Note2: this doesn’t affect accessing the keys in the params hash like params[:city]. You can view the Pull Request that implemented this change.
Some Code Snippets for Rails5.:
Json API
def create photos = [] photo_params.each do |p| photo = Photo.new(p) photos << photo if photo.save end render json: photos, status: 201 end def photo_params params.require(:photos).map do |p| ActionController::Parameters.new(p.to_hash).permit(:title, :src) end
Mandrill inbound webhooks
params = ActionController::Parameters.new( mandrill_events: [ msg: name: 'Francesco', age: 22, role: 'admin' , msg: name: 'steve', age: 22, role: 'admin' ] ) permitted = params.require(:mandrill_events).map # => ["name"=>"Francesco", "age"=>22, "name"=>"steve", "age"=>22]
Params hash in RSpec in Rails 5?
expect_any_instance_of(Hospital).to receive(:update).with(ActionController::Parameters.new('name':'MyString'))
Hey Guys! Hope you enjoyed this session :).If you like it then please share and let us know your views as well, we will try to answer your quetions.
For any proffesional assistance you can checkout our Ruby on Rails Application Development services or contact us.
0 notes