1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your suggestions works, thanks! I'll start playing around with it a bit. I'll wait a bit before accepting your answer to see if i can get some more answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.