【问题标题】:How to assign User_id to an item如何将 User_id 分配给项目
【发布时间】:2019-12-30 00:06:16
【问题描述】:

所以我有储物柜模型,它只是一个基本的脚手架

  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

也是一个只是基本设计的用户模型。

我希望用户能够选择他们想要的储物柜,

所以我想列出所有储物柜,然后用户点击选择按钮,然后储物柜被分配给用户,即 locker_id 更新给当前用户

这是我的控制器

  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

【问题讨论】:

  • 你想达到什么目的?到目前为止,你自己做了什么?你需要帮助弄清楚什么?你能添加更多代码吗?

标签: ruby-on-rails ruby rubygems ruby-on-rails-5


【解决方案1】:

制作一个控制器方法来更新当前用户的储物柜。

放置 /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

这真是丑陋的代码,做了一些假设......但这不是你想要做的吗?

【讨论】:

  • 这假定储物柜上有belongs_to :user。而 findById(即使是正确的形式 find_by_id)自 rails 4 以来已被弃用。但除此之外,是的,大致就是这个形状。
  • 这与我正在尝试做的类似,但我的视图会是什么样子?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 2012-12-12
  • 1970-01-01
  • 2021-12-20
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多