I have a situation that I can’t seem to find an answer for. I have a
view for a new “report” I want it to be possible for the user to input
a company name and location if they aren’t already in the list of
“known” values and when the form is submitted I want those manual
entries added to their respective tables at the same time the report
is added.
How would I go about doing this? I’ve tried creating new_company and
new_location fields in the view and looking for them in the controller
but they are never set in the params hash.
Below is the relevant code:
CONTROLLER:
def create
@report = Report.new(params[:report])
# If they entered a location that wasn't listed we need to add it
if params[:new_location]
@location = Location.new
@location.city = params[:new_location][0]
@location.region = params[:new_location][1]
@location.country = params[:new_location][2]
@location.save
end
# Similar to above but if they entered a company that wasn't lited
if params[:new_company]
@company = Company.new
@company.name = params[:new_company]
if params[:new_location]
@company.location_id = @location.id
end
@company.save
end
# And again for a new position
if params[:new_position]
@position = Position.new
@position.name = params[:new_position]
if params[:new_company]
@position.company_id = @company
end
@position.save
end
if @report.save
flash[:notice] = params.to_s
redirect_to :action => 'list'
else
render :action => 'new'
end
end
VIEW:
Title
<%= text_field 'report', 'title' %>
Company: <%= options_from_collection_for_select(@companies, :id, :name, @selected) %>
Other: <%= text_field 'report', 'company_id' %>
Position: <%= options_from_collection_for_select(@positions, :id, :name, @selected) %>
Other: <%= text_field 'report', 'position_id' %>
Category: <%= options_from_collection_for_select(@categories, :id, :name, @selected) %>
Other: <%= text_field 'report', 'category_id' %>
Thanks in advance,
Glen