Andre Pereira Andre Pereira - 1 month ago 11
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 = Reservation.new(reservation_params)
init_date = params[:date].to_s + " " + params[:hour].to_s + ":00"

@reservation.date = init_date.to_datetime
@reservation.date_end = (@reservation.date.to_time + @reservation.duration.hours).to_datetime


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

@business.reservations << @reservation

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


My helpers are defined as:

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

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


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

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.