3

我有个问题。有一种形式,需要传入两个值和两个对象(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 %>

试图通过对象隐藏字段。但是它们以这种形式传递

 <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;" />

如何通过 form_for rails 传递对象?

4

1 回答 1

4

value:选项设置为最终会在每个实例teamh上调用该方法,从而导致您看到的乱码。您应该传递一些唯一标识每个团队的标识符,例如他们的数据库 ID。例如,您可以将其更改为:#to_s#&lt;Team:0x00000002db46b8&gt;

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

在您的接收操作中,您的控制器代码可能如下所示:

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

Score.create team1: d, team2: k, team1_score: 1, team2_score: 3
于 2013-04-03T07:31:33.627 回答