2017-07-07 86 views
0

我有一個帶有索引視圖的主控制器,就像一個搜索框,讓用戶通過選擇框查詢第一個表或第二個表。用戶輸入搜索詞後,他將被重定向到第一個或第二個模型的索引頁以及該模型的搜索結果。簡單的形式:從另一個控制器創建一個新的記錄

每次使用搜索類型和搜索詞提交查詢時,都必須創建搜索記錄。但是,我不知道如何使用來自不同控制器的simple_form創建新的搜索對象,這是本例中的主控制器。

家庭控制器

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 
+0

發佈完整的'finds_cntroller' – Pavan

回答

1

未經許可參數:找到

find_params應該只是

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

你應該訪問search_typeparams[: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

+0

'搜索'是查詢表的更好名稱嗎? –

+0

@JunDalisay這可能是一個更好的名字,但要小心,當你使用任何寶石來實現搜索。大部分寶石都使用'search'作爲方法名稱 – Pavan

+0

非常感謝! –

0

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

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

OR

@find = Find.create!(find_params) 

此外,強大的參數應該是

def find_params 
    params.require(:find).permit(:search_term, :search_type) 
end 
相關問題