使用Ransack时如何验证输入



我使用Ransack创建了一个带有多个搜索栏的搜索表单,并意识到即使模型中有validates代码,我仍然会得到一些输入栏为空的搜索结果。

ticket.rb

class Ticket < ApplicationRecord
validates :departure, presence: true
validates :arrival, presence: true 
validates :departure_date, presence: true

end

有人知道在使用Ransack时如何验证正确的方法吗?

您会理解复杂的验证流。您的模型在验证后收到错误,控制器在后期操作时回退以呈现编辑表单,并且表单字段显示错误。简称:

app/controllers/companies_controller.rb:

class CompanyController < ApplicationController
def index
@search = CompanySearchForm.new(name: company_search_params[:name])
@search.validate
@companies = Company.ransack(name_eq: company_search_params[:name]).result
end
...
private
def company_search_params
params.require(:company_search_form).permit(:name)
end
def search_form
form = ::CompanySearchForm.new(name: company_search_params[:name])
form.validate
form
end
end

app/forms/copmany_search_form.rb

class CompanySearchForm
extend ActiveModel::Naming
extend ActiveModel::Translation
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Validations::Callbacks
include ActiveRecord::AttributeAssignment
attr_reader :name
def initialize(name:)
@name = name
end
def validate
errors.add(:name, 'search string is too long.') if name.size > 5
end
end

app/views/companies/index.html.haml

= simple_form_for(@search, url: companies_path, method: :get) do |f|
= f.input :name
= submit_tag('Search', class: 'btn')
%table
= @companies.each do |company|
%tr
%td= company.id
%td= company.name

关于工作示例,请点击此处

相关内容

  • 没有找到相关文章

最新更新