我想要实现的是一个产品索引页面,其中显示:
(1)与数据库中的记录匹配的搜索结果
(2)如果用户输入为空白(或者如果我只是访问/ products页面),则是我的所有产品,并且
(3)一条消息,指出如果该产品不存在(不在数据库中),则找不到该产品。
如果我在搜索字段中插入空格,或者如果插入的字符串与数据库中的任何记录都不匹配,那么下面的代码将为我返回所有产品;如果在数据库中找到了正确的产品,则返回以下代码。
<div class="container">
<div class="row">
<% if @products_search.present? %>
<% @products_search.each do |product| %>
<div class="col-sm-8 col-sm-offset-2">
<%= product.name %><br>
<%= product.description %><br>
<%= humanized_money_with_symbol(product.price)%><br>
<%= link_to "Show Product", product_path(product) %>
</div>
<% end %>
<% elsif @products_search.blank? %>
<% @products.each do |product| %>
<div class="col-sm-8 col-sm-offset-2">
<%= product.name %><br>
<%= product.description %><br>
<%= humanized_money_with_symbol(product.price)%><br>
<%= link_to "Show Product", product_path(product) %>
</div>
<% end %>
<% else %>
<h1>No products found!</h1>
<% end %>
</div>
</div>
class ProductsController < ApplicationController
def index
@products_search = Product.search_by_name_and_description(params[:term])
@products = Product.all
end
end
class Product < ApplicationRecord
has_and_belongs_to_many :orders
belongs_to :category
belongs_to :user
monetize :price_cents
include PgSearch
pg_search_scope :search_by_name_and_description,
against: [ :name, :description ],
associated_against: {
category: [ :name ]
},
using: {
tsearch: { prefix: true }
}
end
<%= form_tag products_path, method: :get do %>
<%= text_field_tag 'term', params[:term], placeholder: "What are you looking for?", :required => true %>
<%= submit_tag 'Search!' %>
<% end %>
<br>
答案 0 :(得分:0)
(1)如果搜索结果与数据库中的记录匹配,
(2)如果用户输入为空(或者我只是访问/ products页面),则我的所有产品,并且
(3)一条消息,指出如果该产品不存在(不在数据库中),则找不到该产品。
#include <iostream>
#include <SDL.h>
#undef main
using namespace std;
int SCREEN_WIDTH = 650;
int SCREEN_HEIGHT = 650;
int main() {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
SDL_Window *window = SDL_CreateWindow("Cells", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == nullptr) {
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr) {
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
SDL_DestroyWindow(window);
SDL_Quit();
return 1;
}
SDL_Event event;
bool quit = false;
while (!quit) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
quit = true;
}
}
SDL_RenderClear(renderer);
// renderTextures
SDL_Rect fillRect = { 122, 122, 122, 122};
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &fillRect);
SDL_RenderPresent(renderer);
}
return 0;
}
答案 1 :(得分:0)
有了这段代码,我终于实现了我想做的事情。
.txt