Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

Rails 3 submit a form with multiple records

I'm new to rails so this is probably a basic question. I am trying to create a form where the user can create 3 records at once. I want the user to only have to click the submit button once. I'm submitting to my Review model a name, comment, and rating. Currently, only the last record is entered into the database.

<%= form_for([@user,@review]) do |f| %>
<table>
  <tr>
    <td>Rank</td>
    <td>Name</td>
    <td>Comment</td>
  </tr>
  <tr>
    <td>1</td>
    <td><%= f.text_field :name %></td>
    <td><%= f.text_field :comment %></td>
    <%= f.hidden_field :rating, :value=> "5" %>
  </tr>
  <tr>
    <td>2</td>
    <td><%= f.text_field :name %></td>
    <td><%= f.text_field :comment %></td>
    <%= f.hidden_field :rating, :value=> "3" %> 
  </tr>
  <tr>
    <td>3</td>
    <td><%= f.text_field :name %></td>
    <td><%= f.text_field :comment %></td>
    <%= f.hidden_field :rating, :value=> "1" %>
  </tr>
</table>
  <div class="actions">
    <%= f.submit "Create my top 3" %>
  </div>
<% end %>

Any advice is appreciated. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would recommend using fields_for for this:

<%= form_for([@user, :reviews]) do |f| %>
  <% @reviews.each do |review| %>
    <%= fields_for review do |r| %>
      <%= render "reviews/form", :r => r %>
    <% end %>
  <% end %>
<% end %>

To make this work, you will need to build as many review objects as you require in your controller:

def new
  # you could also have this in a before_filter...
  @user = User.find(params[:id])
  @reviews = Array.new(3) { @user.reviews.build }
end

This would create new instances of review records for this user, which is different from new records. Instances are simply Ruby objects. Now because you've called @user.reviews.build three times, you'll see three reviews in your view.

def create
  @user = User.find(params[:id])

  @reviews = Review.create(params[:reviews])
  # Some more logic for validating the parameters passed in
end

This will create three new Review objects and link them to @user, assuming all three are valid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...