如何根据Rails 5中的select选项从数据库中进行搜索输入

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何根据Rails 5中的select选项从数据库中进行搜索输入相关的知识,希望对你有一定的参考价值。

所以我有一个表单,其中输入(类型:文本)和选择选项彼此相邻。我希望能够从选择选项(“从食物中搜索”或“搜索食物”)中选择一个选项,以便从数据库中的相应表格中进行搜索。例如:您可以从选择选项“从食物中搜索”中进行选择,因此在文本输入中查询“user_food”表。如果您选择“搜索食物”,则查询“食物”表。哦,顺便说一句,我使用Sqlite3作为数据库(Rails的标准)。

这是输入到目前为止的样子:

enter image description here

这是它的代码:enter image description here

任何帮助,将不胜感激!提前致谢!

答案

视图:

<%= select_tag :food_selection, options_for_select([['Search for food', 'foods'], ['Search your food', 'user_foods']]) %>

调节器

if params[:selection] == 'foods'
  @foods = Food.where('...')
else
  @foods = UserFood.where('...')
end

@foods = @foods.limit(20) # chain methods here they both share

以上是关于如何根据Rails 5中的select选项从数据库中进行搜索输入的主要内容,如果未能解决你的问题,请参考以下文章