如何在 Rails 中执行用户输入 [英] How to perform user input in rails

查看:30
本文介绍了如何在 Rails 中执行用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为此苦苦挣扎了一段时间(阅读了大量关于导轨的红宝石以尝试理解这一点),但我不确定用户输入是如何工作的.

I've been struggling for a while on this (been reading a lot of the ruby on rail guides to try and understand this), but I'm not sure how user inputs work.

我正在尝试使用用户指定的字段列表(美食、邮政编码、评论分数)在我的数据库中搜索餐厅.我创建了一个 html.erb 页面,其中包含所有这些选项.

I am trying to search for a restaurant in my database with a list of fields the user specifies (cuisine, zipcode, review score). I have created a html.erb page that has the options for all of these.

这是我的控制器.

class WelcomeController < ApplicationController
        def home
            @my_search = Restaurant.joins(:inspection).where(cuisine: c, zipcode: z, totalscore: 1..h)
        end

我的餐厅和检查模型也有它们之间的关系(外键).

My models for restaurant and inspection also have relations between them (the foreign keys).

您将如何让用户输入 c(美食)、z(邮政编码)和 1..h(分数范围)的输入?

How would you go about letting the user give inputs for c (cuisine), z (zipcode) and 1..h (score range)?

我知道过去人们已经回答过这个问题,但我认为我需要一个具体的例子来真正理解如何做到这一点.比如,你会在 html.erb 代码中放什么,以便在选择一个选项时,将该值传递给该方法?

I know that people have answered this question in the past, but I think I need a concrete example to actually understand how to do this. As in, what would you put in the html.erb code so that when an option is selected, that value is passed to the method?

谢谢

推荐答案

首先需要在视图中创建一个表单.最简单的方法是使用 form_tag:

First you need to create a form in the view. The simplest way to do this is with form_tag:

<%= form_tag(home_path) do %>
  <%= text_field_tag 'cuisine' %>
  ...other inputs
<% end %>

接下来,确保您在 config/routes.rb 中为您的控制器操作定义了一个路由

Next, make sure you have a route defined for your controller action in config/routes.rb

post 'home' => 'welcome#home'

很可能您的路线看起来会有所不同,但这是您需要的最低限度.

Most likely your routes will look different but this is the bare minimum you need.

在您的控制器中,您可以使用 params 对象访问提交的数据

And in your controller you can access the submitted data using the params object

class WelcomeController < ApplicationController
  def home
    @restaurants = Restaurant.joins(:inspection).where(
      cuisine: params[:cuisine],
      # ...other params
    )
  end
end

这篇关于如何在 Rails 中执行用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆