2011-06-27 52 views
0

我有以下型号:如何建立一个嵌套形式

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

routes文件

resources :polls do 
    resources :poll_votes 
    end 

建议/建议我如何能建立表单,让用户投票? thxs

+0

不是一个真正的答案,但看看这个http://railscasts.com/episodes/196-nested-model-form-part-1(和系列中的下一个),看看Ryan Bates解释过的非常相似的东西。 – Dogbert

+0

谢谢我已经很接近但不够类似于我解决这个 – AnApprentice

回答

0

你见过嵌套窗体的railscasts吗?

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

您可能需要作出一些变化,如果你正在使用Rails 3

+0

谢谢,从那开始。是的,我使用rails 3 – AnApprentice

+0

是的,我发布后,我看到了ruby-on-rails-3标签:)。任何运气,还是你仍然坚持? –

+0

仍然卡住。这很容易做到这一点非轨道。但是用这些表单标签做正确的轨道非常困难! – AnApprentice

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