【发布时间】:2016-12-08 16:32:40
【问题描述】:
虽然我之前问过这个问题,但还没有解决。 我有一个学生模型,其中包含 NAME、SCHOOLNAME、PARENTNAME 等列。 我现在要做的是进行搜索,当用户可以使用以下列名称进行搜索时...... 例如:如果用户在搜索栏中输入 NAME,那么他应该得到所有学生的名字,如果用户使用 SCHOOL NAME 进行搜索,那么他应该得到所有学校名称...... 我尝试了很多但没有达到我想要的 帮助将不胜感激...谢谢
很抱歉没有以适当的方式添加此问题。
在我的项目中添加@fbelanger 解决方案后,实际上什么都没发生,无论我搜索它给我相同的结果...
我的控制器
class DataController < ApplicationController
before_action :set_datum, only: [:show, :edit, :update, :destroy]
# GET /data
# GET /data.json
def index
@data = Datum.all
query = params[:query]
Datum.all.map(&:query) if Datum::QUERIABLE.include?(query)
end
# GET /data/1
# GET /data/1.json
def show
end
# GET /data/new
def new
@datum = Datum.new
end
# GET /data/1/edit
def edit
end
# POST /data
# POST /data.json
def create
@datum = Datum.new(datum_params)
respond_to do |format|
if @datum.save
format.html { redirect_to @datum, notice: 'Datum was successfully created.' }
format.json { render :show, status: :created, location: @datum }
else
format.html { render :new }
format.json { render json: @datum.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /data/1
# PATCH/PUT /data/1.json
def update
respond_to do |format|
if @datum.update(datum_params)
format.html { redirect_to @datum, notice: 'Datum was successfully updated.' }
format.json { render :show, status: :ok, location: @datum }
else
format.html { render :edit }
format.json { render json: @datum.errors, status: :unprocessable_entity }
end
end
end
# DELETE /data/1
# DELETE /data/1.json
def destroy
@datum.destroy
respond_to do |format|
format.html { redirect_to data_url, notice: 'Datum was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_datum
@datum = Datum.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def datum_params
params.require(:datum).permit(:name, :school, :hospital, :city, :food)
end
end
我的模型
class Datum < ActiveRecord::Base
QUERIABLE = %w(name city)
end
我的索引
<p id="notice"><%= notice %></p>
<h1>Listing Data</h1>
<%= form_tag(data_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search here" %>
<%= submit_tag "Search" %>
<% end %>
<table>
<thead>
<tr>
<th>Name</th>
<th>School</th>
<th>Hospital</th>
<th>City</th>
<th>Food</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @data.each do |datum| %>
<tr>
<td><%= datum.name %></td>
<td><%= datum.school %></td>
<td><%= datum.hospital %></td>
<td><%= datum.city %></td>
<td><%= datum.food %></td>
<td><%= link_to 'Show', datum %></td>
<td><%= link_to 'Edit', edit_datum_path(datum) %></td>
<td><%= link_to 'Destroy', datum, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Datum', new_datum_path %>
【问题讨论】:
-
我记得我之前回答过这个问题。它不工作吗? stackoverflow.com/questions/40955019/…
-
^ 哇,同样的人,同样的问题,同样的答案。
标签: ruby-on-rails search