Andre Pereira Andre Pereira - 1 year ago 86
Ruby Question

Access nested params in Rails - attributes from checkbox

I'm trying to access the users array that I get from a check box, to add to an HABTM association between a Reservation and User model.

The params hash is the following:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"vx0dTg8Q2XpyFcXpmmiwbwtFwNiRO25CQImGBasArDZjEbOmjh2lkBSdQGl8Z2Sgr7+kF2qveergEFjZr63AHQ==", "reservation"=>{"name"=>"daads", "phone"=>"", "email"=>"", "number_people"=>"1", "duration"=>"1", "address"=>"", "description"=>"", "users"=>["", "3", "2"]}, "commit"=>"Create Reservation", "date"=>"2016-10-30", "hour"=>"01:30", "id"=>"1"}

My method code is:

def add_reservation
@business = Business.find(params[:id])
@reservation =
init_date = params[:date].to_s + " " + params[:hour].to_s + ":00" = init_date.to_datetime
@reservation.date_end = ( + @reservation.duration.hours).to_datetime

user_reservation_params[:users].each do |u|
@reservation.users << u

@business.reservations << @reservation

flash[:success] = "Reservation added!"
redirect_to business_path(@business)

My helpers are defined as:

def reservation_params
params.require(:reservation).permit(:name, :email, :address, :phone, :duration, :date, :date_end, :number_people, :description)

def user_reservation_params
params.require(:reservation).permit(:users => [])

The way I'm currently accessing the users part of params hash gives me empty variables... How am I supposed to access those values?

Answer Source

You can access them simply as params[:reservation][:users], no need to use strong params for this, since they are not used in mass assignment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download