Philip
Philip

Reputation: 7166

Ruby On Rails Form with integers titles instead of numbers in a drop-select-list

Hi I'm pretty new with Ruby On Rails, and came across this problem.

I have 4 tables, and 1 that has the three others connected to it.

  1. Sportcategories - name of each category
  2. Sports - Name of each sport
  3. Clubs - Name of each club
  4. Results, t.integer "sportcategory_id" t.integer "sport_id" t.integer "club_id"

I have managed to make a simple edit form with text_field for each field in results. But how can I get the names for the integers instead of the numbers?

<%= form_for(@result) do |f| %>
  #if...
  #..
  #end
  <div class="field">
    <%= f.label :sportcategory_id%><br />
    <%= f.text_field :sportcategory_id%>
  </div>
  <div class="field">
    <%= f.label :sport_id %><br />
    <%= f.text_field :sport_id %>
  </div>
  <div class="field">
    <%= f.label :club_id %><br />
    <%= f.text_field :club_id %>
  </div>
  <div class="field">
    <%= f.label :result %><br />
    <%= f.text_field :result %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I have made it so that SportCat, Sports and clubs has many results and that results belongs to all of them.

This is my controller file for results with edit & update

  def edit
    @result = Price.find(params[:id])
  end

  def update
    @price = Price.find(params[:id])

    respond_to do |format|
      if @price.update_attributes(params[:price])
        format.html { redirect_to(@price, :notice => 'Price was successfully updated.') }
        format.xml { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml { render :xml => @price.errors, :status => :unprocessable_entity }
      end
    end

  end

And question two might be answered in question one, but I want to be able to choose from a drop-down list from all the available categories, sports and clubs with their actual name and then pass the right ID when I update it.

Upvotes: 0

Views: 1612

Answers (1)

Reuben Mallaby
Reuben Mallaby

Reputation: 5767

Check the Rails Form select helper

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

<%= form_for(@result) do |f| %>
  <div class="field">
    <%= f.label :sportcategory_id%><br />
    <%= f.select :sportcategory_id, @sportcategories.map {|s| [s.name, s.id]} %>
   </div>   
  <div class="field">
    <%= f.label :sport_id %><br />
    <%= f.select :sport_id, @sports.map {|s| [s.name, s.id]}  %>
 </div>
 <div class="field">
    <%= f.label :club_id %><br />
    <%= f.select :club_id, @clubs.map {|c| [c.name, c.id]}  %>
 </div>
 <div class="field">
    <%= f.label :result %><br />
    <%= f.text_field :result %>
 </div>
 <div class="actions">
    <%= f.submit %>
 </div>

<% end %>

Get @sportcategories, @sports, @clubs in your controller actions.

Upvotes: 4

Related Questions