简单形式:从另一个控制器创建新记录

Simple Form: creating a new record from another controller

我有一个带有索引视图的主控制器,它的作用类似于搜索框,让用户可以通过 select 框查询第一个 Table 或第二个 Table。用户输入搜索词后,他将被重定向到第一个或第二个模型的索引页面,其中包含该模型的搜索结果。

每次提交带有搜索类型和搜索词的查询时,都必须创建搜索记录。但是,我不知道如何使用来自不同控制器的 simple_form 创建新的搜索对象,在这种情况下是 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

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

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

@find = Find.create!(find_params)

还有,强参数应该是

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

Unpermitted parameter: :find

你的find_params应该只是

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

您应该使用 params[:find][:search_type]

访问 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

冲突