Rails 客户端集合验证失败 - 简单表单

Rails Client side Collection Validation fails - Simple Form

我必须构建一个允许用户借阅书籍的简单应用程序。简单地说,一个用户可以创建书籍,他们可以选择另一个用户来借书。

我有三个型号 UserBookLoan:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_many :books
  has_many :loans, through: :books
  has_many :borrowings, class_name: "Loan"

  validates :username, uniqueness: true
  validates :username, presence: true
end

class Book < ActiveRecord::Base
  belongs_to :user
  has_many :loans

  validates :title, :author, presence: true
end

class Loan < ActiveRecord::Base
  belongs_to :user
  belongs_to :book

  validates :user, :book, :status, presence: true
end

LoansController 看起来像这样:

class LoansController < ApplicationController
  before_action :find_book, only: [:new, :create]

  def new
    @users = User.all
    @loan = Loan.new
    authorize @loan
  end

  def create
    @loan = Loan.new
    @loan.book = @book
    @loan.user = User.find(loan_params[:user_id])
    @loan.status = "loaned"
    authorize @loan
    if @loan.save
      redirect_to :root
    else
      render :new
    end
  end

  private

  def loan_params
    params.require(:loan).permit(:user_id)
  end

  def find_book
    @book = Book.find(params[:book_id])
  end
end

我的表单如下所示:

<%= simple_form_for([@book, @loan]) do |f| %>
  <%= f.input :user_id, collection: @users.map { |user| [user.username, user.id] }, prompt: "Select a User" %>
  <%= f.submit %>
<% end %>

如果我在没有选择用户的情况下提交表单,并保留 "Select a User" 提示选项,则表单已提交并且应用程序崩溃,因为它 can't find a user with id=

我不知道为什么表单中的用户存在验证不起作用...

您将更改创建方法

  def create
    @loan = Loan.new
    @loan.book = @book
    @loan.user = User.find_by_id(loan_params[:user_id])
    @loan.status = "loaned"
    authorize @loan
    if @loan.save
      redirect_to :root
    else
      render :new
    end
  end