[英]How to assign User_id to an item
So I have locker model which is just a basic scaffold所以我有储物柜模型,它只是一个基本的脚手架
def change
create_table :lockers do |t|
t.references :user
t.integer :lockerNo
t.string :wing
t.string :sttatus
t.string :comment
t.timestamps
end
end
end
and also a user model which is just basic devise.还有一个用户模型,它只是基本设计。
I want users to be able to select a locker they want,我希望用户能够选择他们想要的储物柜,
So I want to list all the lockers and then users click on Select button and then the locker gets assigned to the user ie the locker_id updates to the current user所以我想列出所有的储物柜,然后用户点击选择按钮,然后储物柜被分配给用户,即 locker_id 更新到当前用户
This is my controller这是我的控制器
before_action :set_locker, only: [:show, :edit, :update, :destroy]
# GET /lockers
# GET /lockers.json
def index
@lockers = Locker.all
end
# POST /lockers
# POST /lockers.json
def create
@locker = Locker.new(locker_params)
respond_to do |format|
if @locker.save
format.html { redirect_to @locker, notice: 'Locker was successfully created.' }
format.json { render :show, status: :created, location: @locker }
else
format.html { render :new }
format.json { render json: @locker.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /lockers/1
# PATCH/PUT /lockers/1.json
def update
respond_to do |format|
if @locker.update(locker_params)
format.html { redirect_to @locker, notice: 'Locker was successfully updated.' }
format.json { render :show, status: :ok, location: @locker }
else
format.html { render :edit }
format.json { render json: @locker.errors, status: :unprocessable_entity }
end
end
end
def assign_locker
if @locker.sttatus = Available
@locker = Locker.find(params[:id])
@locker.user_id = current_user.id
@locker.save
end
redirect_to root_path
end
private
def set_locker
@locker = Locker.find(params[:id])
end
def locker_params
params.require(:locker).permit(:user_id, :lockerNo, :wing, :sttatus, :comment)
end
end
Make a controller method for updating the locker with the current user.制作一个控制器方法来更新当前用户的储物柜。
Put /lockers/[locker_id]放 /lockers/[locker_id]
def update
locker = Locker.findById(params[:locker_id])
locker.user = current_user
if locker.save
head 200
else
head 422
end
end
That's really ugly code that makes a few assumptions... but is it not what you're trying to do?这真是丑陋的代码,做出了一些假设......但这不是你想要做的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.