I'm just starting with RoR and i got an issue.
Earlier, I asked hear and nobody could fix it. I would like to make a simple search form, where i would search for a product name(title).
Here is the issue: "Couldn't find Product with 'id'=search"
Here is my controller:
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
helper_method :get_cost
# GET /products
def index
@products = Product.all
@products = Product.search(params[:find])
end
# GET /products/1
def show
end
# GET /products/new
def new
@product = Product.new
# ingredients_ids = @product.ingredients
end
# GET /products/1/edit
def edit
end
# POST /products
def create
@product = Product.new(product_params)
if @product.save
redirect_to @product, notice: 'Product was successfully created.'
else
render :new
end
end
# PATCH/PUT /products/1
def update
if @product.update(product_params)
redirect_to @product, notice: 'Product was successfully updated.'
else
render :edit
end
end
# DELETE /products/1
def destroy
@product.destroy
redirect_to products_url, notice: 'Product was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
@product = Product.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def product_params
params.require(:product).permit(:title, :description, :category, :price, :quantity, {ingredient_ids: []})
end
end
Here is my model:
class Product < ActiveRecord::Base
has_and_belongs_to_many :ingredients
has_and_belongs_to_many :orders
enum category: ["Culinária Italiana", "Culinária Oriental", "Culinária Árabe", "Culinária Brasileira"]
TITLE_MIN_LENGTH = 3
DESCRIPTION_MIN_LENGTH = 2
validates :title, presence: true, :length => {:minimum => TITLE_MIN_LENGTH}, uniqueness: true
validates :description, presence: true, :length => {:minimum => DESCRIPTION_MIN_LENGTH}
def self.search(search)
if search
where(["title LIKE ?", "%#{search}%"])
else
all
end
end
end
here is my view:
<%= form_tag(products_search_path, :method => :get) do%>
<%= text_field_tag :find, nil, placeholder:"Insira o que está procurando"%>
<%= submit_tag "Pesquisar", :name => nil %>
<% end %>
And just to finish, here is my routes:
Rails.application.routes.draw do
get 'sessions/new'
get 'users/new'
get 'orders/show'
get 'orders/new'
resources :ingredients
resources :products do
get 'search'
end
resources :orders
root "home#index"
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get 'home/about'
get 'home/contact'
get "home" => "home#index"
end
Thanks for the attention, Miguel.
Aucun commentaire:
Enregistrer un commentaire