0

我有一个带有索引视图的 Home 控制器,它就像一个搜索框,让用户通过选择框查询第一个表或第二个表。用户输入搜索词后,他将被重定向到第一个或第二个模型的索引页面,其中包含该模型的搜索结果。

每次使用搜索类型和搜索词提交查询时,都必须创建搜索记录。但是,我不知道如何使用来自不同控制器的 simple_form 创建一个新的 Search 对象,在这种情况下是 Home 控制器。

家庭控制器

def index
  @find = Find.new

主页 索引视图

= simple_form_for @find, url: finds_path, method: :post do |f|
  = f.input :search_type, :collection => [['First', 'First'], ['Second', 'Second']]
  = f.input :search_term
  = f.button :submit

找到控制器

def new
  @find = Find.new
end

def create
  @find = Find.new(find_params)
  if params[:search_type] == 'First'
    redirect_to first_path
  elsif params[:search_type] == 'Second'
    redirect_to second_path
  else
    redirect_to root_path
  end
end

private

def find_params
  params.permit(:search_term, :search_type, :utf8, :authenticity_token, 
    :find, :commit, :locale)
  # the params seem to come from the Home controller so I added them just to see if they will go through :(
end

它不保存。相反,它给出:

Started POST "/en/finds"
Processing by FindsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"..", "find"=>{"search_type"=>"First", "search_term"=>"Something"}, "commit"=>"Create Find", "locale"=>"en"}
Unpermitted parameter: :find
Redirected to http://localhost:3000/en
4

2 回答 2

1

不允许的参数::find

find_params应该只是

def find_params
  params.require(:find).permit(:search_type, :search_term)
end

您应该访问search_typewithparams[:find][:search_type]

if params[:find][:search_type] == 'First'
  redirect_to first_path
elsif params[:find][:search_type] == 'Second'
  redirect_to second_path
  else
  redirect_to root_path
end

另外,我建议重命名Find模型,因为它与ActiveRecord#FinderMethods

于 2017-07-07T07:55:41.833 回答
0

您需要保存,您只是在初始化属性..

@find = Find.new(find_params)
@find.save!

或者

@find = Find.create!(find_params)

此外,强参数应该是

def find_params
  params.require(:find).permit(:search_term, :search_type)
end
于 2017-07-07T07:53:31.420 回答