marius2k12
marius2k12

Reputation: 1101

Ruby on Rails - Nested Form

My app has Users who bet on matches. A single bet is called a "tipp".

I have the following (working) form where Users can EDIT their bets:

<%= form_for @user, :url => { :action => "update_tipps" }  do |user_form| %>

    <%= user_form.fields_for :tipps do |tipp_form, index| %>
        <%= tipp_form.text_field :tipp1 %><br/>
        <%= tipp_form.text_field :tipp2 %><br/>         
    <% end %>

    <%= submit_or_cancel(user_form) %> 
<% end %>

With this form a User can edit all of his bets / tipps at once.

My question:

How can i specify the tipps which a user can edit? I dont want a user to get a list of all his bets, but just a subset of his bets.

For example like this:

<%= user_form.fields_for :tipps.where("match_id = ?", 5) do |tipp_form, index| %>
    <%= tipp_form.text_field :tipp1 %><br/>
    <%= tipp_form.text_field :tipp2 %><br/>         
<% end %>

This would reduce the bets to one bet on a match with ID of 5. This code however doesnt work.

What is the right way to solve this? Thanks in advance.

Upvotes: 1

Views: 128

Answers (1)

MBO
MBO

Reputation: 30985

I haven't tested it right now, but you should be able to pass object to fields_for, bo something like this should work:

<% user_form.object.tipps.where("match_id = ?", 5).each do |tipp| %>
  <%= user_form.fields_for :tipps, tipp do |tipp_form, index| %>
    <%= tipp_form.text_field :tipp1 %><br/>
    <%= tipp_form.text_field :tipp2 %><br/>         
  <% end %>
<% end %>

Of course you should refactor it, because filtering like this (low level search methods) in views is bad smell, but at last you have something to start playing with.

It is described at http://api.rubyonrails.org, search for fields_for method in ActionView::Helpers::FormHelper and description for one-to-many relationship in nested attributes examples.

Upvotes: 1

Related Questions