複数の列を含む検索モデルがあります。これらの列は、の共通form_for @search do |s|
で埋められますapp/views/searchings/index.html.erb
。つまり、そのビューに3つのフィールドがあり、それぞれが独自のチェックボックスでアクティブになっているということです。少なくとも1つのフィールドの存在を検証したいと思います。検証なしでテストしました。入力フィールドが無効になっている場合、その値はnil
です。コードは次のとおりです。
app / models / searching.rb
class Searching < ActiveRecord::Base
belongs_to :user
validate :capacidad_num
validate :has_a_field
def has_a_field
arr = [self.tipo?, self.capacidad?, self.ubicacion_cont?, self.free_to?, self.free_from?]
if !arr.include?(true)
self.errors.add(:base, 'Debes ingresar al menos one parameter de búsqueda')
end
end
def capacidad_num
if self.capacidad?
if !(self.capacidad.to_i != 0)
self.error.add(:capacidad, 'tiene que ser un número')
end
end
end
end
app / controllers / searchings_controller.rb
class SearchingsController < ApplicationController
before_action :get_search, only: [:show]
def index
@couches = Couch.all
@tipos = Tipoc.all
@search = Searching.new
end
def show
#...show stuff not important
end
def create
@search = Searching.new(params.permit(:tipo, :ubicacion_cont, :capacidad))
respond_to do |format|
if @search.save
format.html { redirect_to @search, notice: "Mostrando resultados de búsqueda" }
format.json { render :show, status: :created, location: @search }
else
format.html { render :index }
format.json { render json: @search.errors, status: :unprocessable_entity }
end
end
end
private
def get_search
@search = Searching.find(params[:id])
end
end
それが役立つ場合は、このモデルのスキーマを次に示します。
create_table "searchings", force: :cascade do |t|
t.integer "tipo"
t.string "ubicacion_cont"
t.integer "capacidad"
t.date "free_from"
t.date "free_to"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
各フィールドのブール値を含む配列を使用して、少なくとも1つのフィールドの存在を確認しようとしましたが、機能していないようです。フォームに値を入力するたびにエラーが発生します。
私は解決策への別のアプローチを得て、うまくいきました。内部のコントローラーでdef create
、params[:searching]
がゼロかどうかを確認します。その場合は、アラートのメッセージを表示します。
def create
if params[:searching].nil?
redirect_to new_searching_path, alert: 'Debes ingresar al menos un parámetro'
else
#do the new and save stuff
end
end
私はbyebug
自分の中で受け取っていたものを使用して確認した後、このソリューションにparams
行き着きましたdef create
。Railsプログラミングの良い習慣ではないことは知っていますが、私が望むのは、それが魅力のように機能することです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加