在rails上验证搜索表单

时间:2015-10-05 09:13:07

标签: ruby-on-rails ruby validation ruby-on-rails-4

我在验证方面遇到了一些问题。我试图验证不属于数据库的params [:search]和params [:miles]。到目前为止,我已经创建了一个无表格模型,但仍需要一些帮助来弄清楚我的代码有什么问题。感谢你的帮助。

user_controller.rb

class UsersController < ApplicationController
  def index
    @search = Search.new(search: params[:search], miles: params[:miles])


    if params[:search] && params[:miles].present?
    @users = User.near(params[:search], params[:miles], units: :mi)
     elsif params[:search].present?
    @users = User.near(params[:search], 10, units: :mi)
    else
     @users = User.all
    end

index.html.erb

  <%= form_for @search, url: users_path, method: :get do |f| %>
    <% if @search.errors.any? %>
      <h2> Errors: </h2>
      <ul>
        <% @search.errors.full_messages do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    <% end %>
    <%= f.label :miles, params[:miles] %>
    <%= f.text_field :miles %>
    <%= f.label :search, params[:search] %>
    <%= f.text_field :search %> </br >
    <%= f.submit "Search" %>
  <% end %>

search.rb模型

class Search
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :search
  attr_accessor :miles

  validates_presence_of :search
  validates :miles, inclusion: { in: 0..9 }
end

1 个答案:

答案 0 :(得分:1)

因此用户访问索引页面并填写搜索字段:searchmiles 然后点击Search并到达索引控制器,在此处创建搜索:@search = Search.new

代码处于任何位置“搜索”是“给定”用户填写的参数。

你不应该这样做:

@search = Search.new(search: params[:search], miles: params[:miles])

@search = Search.new
@search.search = params[:search]
@search.miles = params[:miles]

然后为了启动验证,你需要以某种方式'激活'它们,比如应该触发验证过程的@search.valid?