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

时间:2017-07-07 07:33:03

标签: ruby-on-rails simple-form-for

我有一个带有索引视图的Home控制器,其作用类似于一个搜索框,允许用户通过选择框查询First Table或Second Table。在用户输入搜索词后,他将被重定向到第一个或第二个模型的索引页面以及该模型的搜索结果。

每次使用搜索类型和搜索字词提交查询时,都必须创建搜索记录。但是,我不知道如何使用来自不同控制器的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

2 个答案:

答案 0 :(得分:1)

  

未经许可的参数:: find

您的find_params应该只是

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

您应该使用search_type

访问params[: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冲突

答案 1 :(得分:0)

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

{
    "compilerOptions": {
        ...
    },
    "typeAcquisition": {
        "include": [
            "jasmine"
        ]
    }
}

OR

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

此外,强参数应

@find = Find.create!(find_params)