ActiveRecord构建嵌套资源

时间:2011-07-11 21:31:53

标签: ruby-on-rails activerecord nested-resources

(注意:这里的源代码https://github.com/cthielen/dss-evote

我有一个简单的投票申请。调查是投票的问题集,投票是他们的偏好的每用户实例,投票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只有这个:     资源:调查       资源:选票     端

/ surveys / 1似乎有效,偶数/调查/ 1 /选票。 / 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的原因是偏好代表一个人的答案,偏好的长度可能会从调查变为调查。因此,如果调查有六个问题,@ ballot.survey.questions.length将为6,我需要创建6个空白@ ballot.preferences,然后由form_for表示,并希望使用RESTful Create正确保存。

提前感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分: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| %>