0
我正在學習用Rails 4.0和我使用Cocoon創建一個簡單的投票程序的嵌套形式。NoMethodError使用Rails 4.0和嵌套形式繭
用戶應該能夠添加一個新的問題,然後添加儘可能多的答案,因爲他們想。
我有工作的嵌套形式,但是當我試圖挽救該調查,我收到說NoMethodError in PollsController#create - undefined method ``answer' for #<Poll:0x007fba59a70dd0>
錯誤下面是從我Polls_Controller的相關信息:
before_action :set_poll, only: [:show, :edit, :update, :destroy]
def create
@poll = Poll.new(poll_params)
respond_to do |format|
if @poll.save
format.html { redirect_to @poll, notice: 'Poll was successfully created.' }
format.json { render :show, status: :created, location: @poll }
else
format.html { render :new }
format.json { render json: @poll.errors, status: :unprocessable_entity }
end
end
end
private
def poll_params
params.require(:poll).permit(:question, :expires, answers_attributes: [:id, :answer, :_destroy])
end
投票型號
class Poll < ActiveRecord::Base
has_many :answers, :class_name => "Answer"
accepts_nested_attributes_for :answers, reject_if: :all_blank, allow_destroy: true
validates :answer, presence: true
end
答案和模型
class Answer < ActiveRecord::Base
belongs_to :poll
end
下面是包含輪詢形式和應答(嵌套的)形式在兩個.erb諧音。
_form.html.erb
<%= form_for(@poll) do |f| %>
<% if @poll.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@poll.errors.count, "error") %> prohibited this poll from being saved:</h2>
<ul>
<% @poll.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.label :question %><br>
<%= f.text_field :question, class: "form-control" %>
</div>
<div class="form-group" id="answers">
<%= f.fields_for :answers do |answer| %>
<%= render 'answer_fields', f: answer %>
<% end %>
<div class="links">
<%= link_to_add_association 'Add Answer', f, :answers, class: "btn btn-default add-button" %>
</div>
</div>
<div class="form-group">
<%= f.label :expires %><br>
<%= f.datetime_select :expires %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
_answer.html.erb
<div class="nested-fields form-group">
<div class="field">
<%= f.label :answer %>
<br/>
<%= f.text_field :answer, class: "form-control" %>
</div>
<%= link_to_remove_association "remove answer", f, class: "form-button btn btn-default" %>
</div>
我在這個一直盯着太久儘管它是一個簡單的想法,我的大腦ISN沒有看到這個問題。有任何想法嗎?
編輯這裏是我的架構
ActiveRecord::Schema.define(version: 20151104213600) do
create_table "answers", force: :cascade do |t|
t.text "answer"
t.integer "poll_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "answers", ["poll_id"], name: "index_answers_on_poll_id"
create_table "polls", force: :cascade do |t|
t.string "question"
t.datetime "expires"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
答案模型中的答案文本字段命名答案? – aledustet
@aledustet,我已經更新了OP來顯示schema.rb文件。它被命名爲「答案」 – Ellenbrook
是部分名爲_answer_fields.html.erb或_answer.html.erb,你把你的問題? – aledustet