(注意:源代碼在這裏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