(注意:源代码在这里https://github.com/cthielen/dss-evote)ActiveRecord嵌套资源建设
我有一个简单的投票应用程序。调查是一组要投票的问题,投票是每个用户的偏好实例,以及投票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正确保存。
在此先感谢您提供的任何帮助!
请妥善出示您的问题...谢谢:) – apneadiving