Reputation: 1265
I have a Home controller with an index view that acts like a search box that lets the user query a First Table or Second Table through a select box. After a user enters a search term, he will be redirected to the index page of the First or Second model with the search results for that model.
A Search record must be created each time a query is submitted with the search type and search term. However, I don't know how to create a new Search object using simple_form from a different controller, which is the Home controller in this case.
Home Controller
def index
@find = Find.new
Home Index View
= 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
Finds Controller
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
It doesn't save. Instead it gives:
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
Upvotes: 0
Views: 1498
Reputation: 33542
Unpermitted parameter: :find
Your find_params
should be just
def find_params
params.require(:find).permit(:search_type, :search_term)
end
You should access the search_type
with 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
Also, I would suggest renaming the Find
model as it conflicts with ActiveRecord#FinderMethods
Upvotes: 1
Reputation: 6121
You need to save, you are just initializing the attributes..
@find = Find.new(find_params)
@find.save!
OR
@find = Find.create!(find_params)
Also, strong parameters should be
def find_params
params.require(:find).permit(:search_term, :search_type)
end
Upvotes: 0