Search code examples
ruby-on-railsrubydrop-down-menutextbox

Ruby on Rails: allow the user to enter a new information, OR click on drop down menu to select existing info


New ROR programmer here. I'm trying to build a web application that allows a user to complete a form, where they enter a companies information, and by clicking submit, it adds the input to a database.

At the moment, if the user was to create a new entry, they would see a few fields, for example, "Company Name". There is a blank box for them to put in a new company, and next to that, there is a drop down menu that the user can use to see existing companies in the database.

<div class="field">
<%= f.label :company_name %><br />
<%= f.text_field :company_name %>
<%= f.label :company_name %><br />
<%= f.select( :company_name, Company.all.map {|p| [p.company_name]}.uniq!, :prompt => "Select a Company") %>

I'm looking for a way to allow the user to enter a new company, OR click on the drop down menu and select an existing company.

At the moment: If nothing is entered into textbox and no option from dropdown selected, it is saved as blank. If something is entered, and no option is selected, it is saved as blank. However, if something is entered and something is picked from the dropdown, the dropdown option is saved.

Hopefully I haven't made it too confusing. Any help at all will be appreciated.

Thanks in advance.

EDIT:

My create action now looks like this

 def create
@company = Company.new(params[:company])
@company.company_name = params[:new_company_name] unless params[:new_company_name].empty?

respond_to do |format|
  if @company.save
    format.html { redirect_to @company, notice: 'Company was successfully created.' }
    format.json { render json: @company, status: :created, location: @company }
  else
    format.html { render action: "new" }
    format.json { render json: @company.errors, status: :unprocessable_entity }
  end
end

end

and form view:

<%= label :company_name %><br />
<%= text_field :new_company_name %>

<%= f.label :company_name %><br />
<%= f.select( :company_name, Company.all.map {|p| [p.company_name]}.uniq!, :prompt => "Select a Company") %>

The new error is now:

wrong number of arguments (1 for 2)

Extracted Source: <%= label :company_name %>


Solution

  • You cannot have two params with the same name in your view, as rails won't know what to do with them

    @rodzyn is right, so please give the credits to him.. :)

    Just to clarify:

    your form:

    <%= label_tag :new_company_name, "Company name" %><br />
    <%= text_field_tag :new_company_name %>
    
    <%= f.label :company_name %><br />
    <%= f.select( :company_name, Company.all.map {|p| [p.company_name]}.uniq!, :prompt => "Select a Company") %>
    

    Your controller:

    @company = Company.new(params[:company])
    @company.company_name = params[:new_company_name] unless params[:new_company_name].empty?