3

I have a problem. There is a form in which you need to pass two values ​​and two object (teamh, teamq).

<%= form_for (Score.new) do |f| %>
          <p>

            <%= f.hidden_field :team1, value: teamh %>
            <%= f.hidden_field :team2, value: teamq %>

            <%= f.text_field :team1_score %>
            <%= f.text_field :team2_score %>
          </p>
          <p><%= f.submit "Submit" %></p>
<% end %>

Trying to pass through objects hidden Fields. But they are passed in this form

 <input id="score_team1" name="score[team1]" type="hidden" value="#&lt;Team:0x00000002db46b8&gt;" />
 <input id="score_team2" name="score[team2]" type="hidden" value="#&lt;Team:0x00000003335380&gt;" />

How to pass an object through a form_for rails?

parliament
  • 67
  • 1
  • 8
  • This might help you. http://stackoverflow.com/questions/846936/passing-object-from-view-to-controller# Answer is we cant pass object from rails view to controller. – Srikanth Jeeva Apr 03 '13 at 07:30

1 Answers1

4

Setting the value: option to teamh ends up invoking the #to_s method on each instance, resulting in the #&lt;Team:0x00000002db46b8&gt; gibberish you're seeing. You should instead pass some identifier which uniquely identifies each team, such as their database ID. For instance, you could change this to:

    <%= f.hidden_field :team1_id, value: teamh.id %>
    <%= f.hidden_field :team2_id, value: teamq.id %>

And in your receiving action, your controller code could look like this:

k = Team.find params[:team1_id]
d = Team.find params[:team2_id]

Score.create team1: d, team2: k, team1_score: 1, team2_score: 3
Stuart M
  • 11,458
  • 6
  • 45
  • 59
  • View code is all about taking your objects and representing them as textual HTML. You can't actually represent an object in the rendered page, you can only include a reference that uniquely identifies it, namely its database ID. Can you elaborate on why you "need to pass an object"? – Stuart M Apr 03 '13 at 07:45
  • Thinking about it. I need to pass the object. Is there another way? – parliament Apr 03 '13 at 07:53
  • models require the transfer object, for a bunch of tables – parliament Apr 03 '13 at 07:56
  • Everything coming out of your Rails view has to be in text, which limits you to simple data types like strings, integers, etc. Think about how the data will be passed back to you when the user submits the form via a GET or POST request: it will come back via the `params` hash to your controller, and by that point it will be a simple datatype like String or Integer. – Stuart M Apr 03 '13 at 08:03
  • If you pass the database ID in the form, when the user submits the form, it will pass you the database ID back again, and in the receiving controller action you simply look up the record by its ID and then make any changes to it that are appropriate. – Stuart M Apr 03 '13 at 08:04
  • What other way to pass objects and values of ​​team scores? – parliament Apr 03 '13 at 08:07