如何构建嵌套表单

时间:2011-06-27 22:50:56

标签: ruby-on-rails ruby-on-rails-3

我有以下型号:

class Poll < ActiveRecord::Base
  has_many :poll_votes, :dependent => :destroy
  has_many :poll_options, :dependent => :destroy

class PollOption < ActiveRecord::Base
  belongs_to :poll
  has_many :poll_votes, :dependent => :destroy

class PollVote < ActiveRecord::Base
  belongs_to :user
  belongs_to :poll
  belongs_to :poll_option

我正在尝试做的是构建一个输出民意调查及其选项的表单。允许用户选择选项并提交投票。我正在努力创建表单标签。

这就是我所拥有的:

<%= form_for(@poll, :url => new_poll_poll_vote_path, :remote => true) do |f| %>
 <% @poll.poll_options.each do |poll_option| %>
  <div class="row clearfix" id="poll_option_<%=poll_option.id%>">
  <div class="inputRadio">
  <%= radio_button("poll", "poll_votes", poll_option.id, :class => 'pollVote' ) %>
  </div>
<div class="inputLabel">
  <%= poll_option.title %>
</div>
</div>
<%= f.submit :class => 'button positive', :value => 'Vote' %>
<% end %>

路线档案

  resources :polls do
    resources :poll_votes
  end

建议/建议如何构建表单以允许用户投票? thxs

2 个答案:

答案 0 :(得分:2)

fields_for简化了嵌套表单的内容

class Poll
  accepts_nested_attributes_for :poll_votes
end

在您的视图中...以下拉形式实现,但您可以拆分为单选按钮

<%= form_for(@poll, :remote => true) do |f| %>
  <% f.fields_for :poll_votes do |votes_form| %>
    <%= votes_form.label :poll_option_id, "Your Vote:"%>
    <%= votes_form.collection_select :poll_option_id, @poll.poll_options, :id, :option_text, :prompt => true %>
  <% end %>
  <%= f.submit :class => 'button positive', :value => 'Vote' %>
<% end %>

但是 - 我想你可能只想创建一个民意调查投票......更简单:

控制器:

def show
  ...
  @poll_vote = @poll.poll_votes.build
end

查看:

<%= form_for(@poll_vote, :remote=>true) do |f| %>
  <%= f.collection_select :poll_option_id, @poll_vote.poll.poll_options, :id, :text, :prompt=>true %>
  <%= f.submit, :class=>'button positive', :value=>'Vote' %>
<% end %>

答案 1 :(得分:0)

您是否看过嵌套表单的railscast?

http://railscasts.com/episodes/196-nested-model-form-part-1 http://railscasts.com/episodes/196-nested-model-form-part-2

如果您使用的是Rails 3,则可能需要进行一些更改。