Search code examples
ruby-on-railsruby-on-rails-3.1associationsmodels

Use data from an associated model in a form


I have two models, fixtures and predictions. Fixtures have many predictions.

I would like to have a user fill in a form to predict the scores. The fixture model has all the fixtures pre populated so i would like to use them in the predictions form so that i can create a new prediction record only

How do i grab the data from another model and use it in a form.My fixture model has

:home_team
:away_team
:fixture_date

So in a form i would like to have

Home_team VS Away Team    Enter Home Score   Enter Away Score

Something to that effect, what I would like to know is how to access the data from the fixture model and present it in a form

Would i use collection_select here? though i need to list each fixture individually so I guess that would not work?

Any Help Appreciated

Thanks


Solution

  • I'm not sure I quite follow you, but this may be of help.

    The collection_select that you have mentioned works like this:

    collection_select "model_from_where_you_get_data", "id_of_collection", "SQL_query", "value_of_the_field", "names_of_the_fields_which_are_displayed_to_user", "options{}" (no quotes)
    

    so, for example:

    collection_select :fixtures, :home_team, Fixture.select(:home_team).uniq, :home_team, :home_team, prompt: true
    

    You can simplify this by using fields_for (which btw is what you can use for accessing data via association or adding fields if you need to save some data to that association)

    <%= form_for @prediction do |f| %>
      <%= f.fields_for :fixture do |ff| %>
         <%= ff.collection_select :home_team, Fixture.select(:home_team).uniq, :home_team, :home_team, prompt: true %>
      <% end %>
    <% end %>
    

    I may have made a mess with the pluralization, but shouldn't be a problem if that's what you want.