(注: ソースコードはこちらhttps://github.com/cthielen/dss-evote )
簡単な投票アプリケーションがあります。調査は投票する一連の質問であり、投票はユーザーごとの設定のインスタンスであり、投票には多くの設定があり、これも各ユーザーに固有です。モデリングは次のとおりです。
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 には次のものしかありません: resources :surveys do resources :ballots end
/surveys/1 は /surveys/1/ballots でも動作するようです。/surveys/1/ballots/new で問題が発生します。
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 を作成しようとしている理由は、設定が人の回答を表し、設定の長さが調査ごとに変わる可能性があるためです。したがって、調査に 6 つの質問がある場合、@ballot.survey.questions.length は 6 になり、6 つの空白の @ballot.preferences を作成する必要があります。これは form_for によって表され、うまくいけば RESTful Create を使用して適切に保存されます。
あなたが提供できる助けを前もってありがとう!