Ruby on rails 简单形式:从另一个控制器创建新记录
我有一个带有索引视图的主控制器,它就像一个搜索框,用户可以通过选择框查询第一个表或第二个表。用户输入搜索词后,他将被重定向到第一个或第二个模型的索引页,其中包含该模型的搜索结果 每次提交带有搜索类型和搜索词的查询时,都必须创建搜索记录。但是,我不知道如何从不同的控制器(本例中是主控制器)使用simple_表单创建新的搜索对象 家庭控制器Ruby on rails 简单形式:从另一个控制器创建新记录,ruby-on-rails,simple-form-for,Ruby On Rails,Simple Form For,我有一个带有索引视图的主控制器,它就像一个搜索框,用户可以通过选择框查询第一个表或第二个表。用户输入搜索词后,他将被重定向到第一个或第二个模型的索引页,其中包含该模型的搜索结果 每次提交带有搜索类型和搜索词的查询时,都必须创建搜索记录。但是,我不知道如何从不同的控制器(本例中是主控制器)使用simple_表单创建新的搜索对象 家庭控制器 def index @find = Find.new def new @find = Find.new end def create @find
def index
@find = Find.new
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
主索引视图
= 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 index
@find = Find.new
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!
或
此外,应选择强参数
def find_params
params.require(:find).permit(:search_term, :search_type)
end
不允许的参数::find
您的find_params
应该是
def find_params
params.require(:find).permit(:search_type, :search_term)
end
您应该使用params[:find][:search\u 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
模型,因为它与发布您的完整finds\u cntroller
对于查询表来说,“Search”是一个更好的名称吗?@jundali说它可能是一个更好的名称,但在使用任何gems实现搜索时要小心。大多数gems使用搜索
作为方法名