current_user
current_user

Reputation: 1212

how to write strong parameters in rails

How can i Implement the below create action using strong parameters

  def create
      #@user = User.find(params[:user_id])

       @listing = Listing.find(params[:listing_id])

       if current_user != @listing.user
                       @reservation=Reservation.new(user_id:current_user.id,listing_id:params[:reservation][:listing_id],price:params[:reservation][:price],
                                    total:params[:reservation][:total],start_date:params[:reservation][:sdate],end_date:params[:reservation][:edate],
                                    driver_name:params[:reservation][:driver_name],no_of_passengers:params[:reservation][:no_of_passengers],days:params[:reservation][:days],reservation_status:false,reservation_state: 'PENDING')
    else
        @reservation=Reservation.new(user_id:current_user.id,listing_id:params[:reservation][:listing_id],price:params[:reservation][:price],
                                    total:params[:reservation][:total],start_date:params[:reservation][:sdate],end_date:params[:reservation][:edate],
                                    driver_name:params[:reservation][:driver_name],no_of_passengers:params[:reservation][:no_of_passengers],days:params[:reservation][:days],reservation_status:false,reservation_state: 'BLOCKED')
    end
    @reservation.save
    end

I have all the attributes coming from _form.html.erb accept user_id ,reservation_status and reservation_state.I can permit some attributes as:

def reservation_params  
    params.require(:reservation).permit(:start_date, :end_date, :price, :listing_id,:total,:driver_name,:no_of_passengers,:days)

How can I permit all the attributes including user_id, reservation_status and reservation_state for a user to complete the reservation.

Thanks in advance!

Upvotes: 0

Views: 71

Answers (1)

spickermann
spickermann

Reputation: 107117

I would start with something like this:

def reservation_params
  parameters = params.require(:reservation).permit(
    :listing_id, :sdate, :edate, :driver_name, :no_of_passengers, :days
  )

  parameters.merge!(user_id: current_user.id, reservation_status: false)

  if current_user != listing.user
    parameters.merge!(reservation_state: 'PENDING')
  else
    parameters.merge!(reservation_state: 'BLOCKED')
  end
end

def listing
  @listing ||= Listing.find(params[:listing_id])
end

Upvotes: 2

Related Questions