开发者

How to build a nested form

开发者 https://www.devze.com 2023-03-15 15:26 出处:网络
I have the following models: class Poll < ActiveRecord::Base has_many :poll_votes, :dependent => :destroy

I have the following models:

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

What I'm trying to do is build a form that outputs a Poll and it's options. Allowing the user to select an option and submit a vote. I'm struggling to create the form tag.

Here's what I have:

<%= 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 => 'butto开发者_开发百科n positive', :value => 'Vote' %>
<% end %>

Routes File

  resources :polls do
    resources :poll_votes
  end

Suggestions/advise on how I can build the form to allow a user to vote? thxs


The fields_for simplifies the nested form stuff

class Poll
  accepts_nested_attributes_for :poll_votes
end

In your view... implemented as a drop down, but you could split up into a radio button

<%= 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 %>

BUT --- I think you may want to just create the poll-votes... much simpler:

Controller:

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

View:

<%= 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 %>


Have you seen the railscasts for nested forms?

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

You may need to make some changes if you are using Rails 3.

0

精彩评论

暂无评论...
验证码 换一张
取 消