【发布时间】:2015-09-23 18:29:47
【问题描述】:
我对 Rails 比较陌生,我正在尝试从头开始创建一个食谱应用程序/网站,我没有遵循任何教程或类似的东西。无论如何...我仍处于网站的早期阶段,但我现在到了我想要显示所有不同类型食谱的索引列表的部分。但我想过滤列表,例如:
如果我点击导航栏上的“蔬菜”按钮,我想进入一个只显示不同蔬菜食谱的索引页面。
我已经继续为食谱添加了一个字符串属性,称为“类别”,因此我将能够区分肉类、海鲜、家禽、开胃菜和蔬菜食谱。我的目标是只需要一个控制器“食谱”,并且在索引操作中能够有条件地过滤参数。从而按食物的“类别”过滤列表。但我不确定如何去做。
这是我的食谱控制器:
class RecipesController < ApplicationController
def index
@recipes = Recipe.all
end
def show
@recipe = Recipe.find(params[:id])
end
def new
end
def edit
end
end
这是我的路线文件:
Rails.application.routes.draw do
resources :recipes
get 'vegetables' => 'recipes#vegetables'
get 'poultry' => 'recipes#poultry'
get 'meat' => 'recipes#meat'
get 'seafood' => 'recipes#seafood'
get 'appetizers' => 'recipes#appetizers'
devise_for :users
get 'about' => 'welcome#about'
root to: 'welcome#index'
end
这是包含导航栏的应用程序布局文件:
<!DOCTYPE html>
<html>
<head>
<title>Mrs. P's Cookbook</title>
<link href='https://fonts.googleapis.com/css?family=Mate+SC' rel='stylesheet' type='text/css'>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div class="top-banner">
<h1 class="banner-logo"> <%= link_to "Mrs. P's Cookbook", root_path %></h1>
<nav>
<%= link_to "POULTRY", poultry_path, class: "nav-link" %> |
<%= link_to "MEAT", meat_path, class: "nav-link" %> |
<%= link_to "SEAFOOD", seafood_path, class: "nav-link" %> |
<%= link_to "APPETIZERS", appetizers_path, class: "nav-link" %> |
<%= link_to "VEGETABLES", vegetables_path, class: "nav-link" %> |
<%= link_to "ABOUT", about_path, class: "nav-link" %>
</nav>
<% if current_user %>
Hello <%= current_user.email %>! <%= link_to "Sign out", destroy_user_session_path, method: :delete %>
<% else %>
<%= link_to "Sign In", new_user_session_path %> or
<%= link_to "Sign Up", new_user_registration_path %>
<% end %>
</div>
<div class="white-field">
<%= yield %>
</div>
</body>
</html>
这是我的 Recipe.rb 模型文件:
class Recipe < ActiveRecord::Base
has_many :comments
end
这是我的食谱表:
create_table "recipes", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "category"
end
我在“食谱”视图文件夹中拥有不同的类别视图,蔬菜、肉类、家禽、海鲜和开胃菜。所有视图都是空的,除了一些文本只是说“蔬菜食谱将在此处列出。”、“肉类食谱将在此处列出。”、“海鲜食谱将在此处列出。”等。
我知道我的要求可能是一项艰巨的任务,所以你们能提供的任何帮助我都会非常感激。如果您需要更多信息,请告诉我。
【问题讨论】:
标签: ruby-on-rails scope