简体   繁体   中英

How to pass user id in table from controller Ruby On Rails

I have been struggling all day to pass a user ID from a current user in my application to the sensors table when i create my new sensor

In the sensor Controller i have this code

def create
  @sensor = Sensor.new(sensor_params)

  respond_to do |format|
    if @sensor.save
      format.html { redirect_to @sensor, notice: 'Sensor was successfully created.' }
      format.json { render action: 'show', status: :created, location: @sensor }
    else
      format.html { render action: 'new' }
      format.json { render json: @sensor.errors, status: :unprocessable_entity }
    end
  end
end


def sensor_params
  params.require(:sensor).permit(:name, :typeOfSensor, :privacy,:user_id)
end

I have used this code

 @sensor = current_user.sensors.build(:current_user_id => params[:current_user_id])

But it passes only the id inside the sensor table without the rest of the attributes

How is the correct way to merge the code so that it passes all the parameters (name, typeOfSensor etc and also it passes the id of the user that created this sensor

Thanks in advance

合并确实是答案。

sensor_params.merge(current_user_id: current_user.id) 

are you sure you need the current_user_id from params? you already have the current user, using a param for that is dangerous, a user con edit your code and create a sensor for another user.

justo do

current_user.sensors.build(sensor_params)

and you are done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM