2011-07-11 111 views
1

(注意:源代码在这里https://github.com/cthielen/dss-evoteActiveRecord嵌套资源建设

我有一个简单的投票应用程序。调查是一组要投票的问题,投票是每个用户的偏好实例,以及投票has_many偏好,这对每个用户来说都是独一无二的。这里的造型:

class Ballot < ActiveRecord::Base 
    belongs_to :survey 
    has_many :preferences 
end 

class Survey < ActiveRecord::Base 
    has_many :questions 
    has_many :eligibilities 
    has_many :ballots 

    accepts_nested_attributes_for :questions, :allow_destroy => true 

    attr_accessible :title, :description, :status, :deadline, :questions_attributes 

    def owner 
    Person.find(owner_id) 
    end 
end 

class Question < ActiveRecord::Base 
    belongs_to :survey 
    has_many :preferences 
end 

class Preference < ActiveRecord::Base 
    belongs_to :ballot 
    belongs_to :question 
end 

routes.rb中只有这个: 资源:调查做 资源:投票结束

/调查/ 1似乎工作,甚至/调查/ 1 /选票。 /调查/ 1 /空格/新是我遇到问题:

在ballots_controller.rb:

def new 
    @survey = Survey.find(params[:survey_id]) 

    @ballot = @survey.ballots.build 

    @survey.questions.count.times { @ballot.preferences.build } 

    respond_to do |format| 
    format.html # new.html.erb 
    end 
end 

(对应图)

<%= form_for [@survey, @ballot] do |f| %> 
    <%= f.fields_for @ballot.preferences do |preferences_fields| %> 
    <% for question in @preferences_fields %> 
     <p> 
    <%= f.label question.question %> 
    <%= radio_button(question.id, "preference", "Yes") %> Yes 
    <%= radio_button(question.id, "preference", "No") %> No 
    <%= radio_button(question.id, "preference", "Decline") %> Decline 
    </p> 
    <% end %> 
    <% end %> 

    <div class="actions"> 
    <%= f.submit "Vote" %> 
    </div> 
<% end %> 

结果在误差:

NoMethodError in Ballots#new 

Showing /Users/cthielen/Projects/Work/dss-evote/app/views/ballots/_form.html.erb where line #2 raised: 

undefined method `model_name' for Array:Class 
Extracted source (around line #2): 

1: <%= form_for [@survey, @ballot] do |f| %> 
2: <% f.fields_for @ballot.preferences do |preferences_fields| %> 
3:  <% for question in @preferences_fields %> 
4:  <p> 
5:  <%= f.label question.question %> 

现在,它看起来正在形成一个数组而不是正确的类的实例,但我不知道如何妥善解决此问题。

编辑:我应该提及我试图构建@ ballot.preferences的原因是,偏好代表一个人的答案,并且偏好的长度可能会从调查变为调查。因此,如果一项调查有六个问题,@ ballot.survey.questions.length将为6,我需要创建6个空白@ ballot.preferences,然后将由form_for表示并希望使用RESTful Create正确保存。

在此先感谢您提供的任何帮助!

+0

请妥善出示您的问题...谢谢:) – apneadiving

回答

1

好的,这是由于这一行:

@ballot.preferences = @survey.questions.map{|question| question.preferences.build} 

由于映射创建其不能由form_helper使用(通常期望通过一个ActiveRecord关系提供了一种型号名称)的数组。

你应该坚持这样的:

@survey.questions.count.times { @ballot.preferences.build } 

旁注:

<% fields_for @ballot.preferences do |preferences_fields| %> 

应该是:

<%= f.fields_for :preferences do |preferences_field| %> 
+0

对不起格式化,我想我已经纠正了大部分。 – Christopher

+0

因此,我添加了一条关于为什么要创建@ ballot.preferences的说明 - 基本上,如果调查有六个问题,我需要提前创建六个空的@ ballot.preferences。那有意义吗? – Christopher

+0

确定了它并编辑了我的答案 – apneadiving