1

红宝石版本:2.0

导轨版本:4.0

我有一个控制器Question,它有一个模型的嵌入式表单Answer

问题.rb

class Question < ActiveRecord::Base
    has_many :answers, :dependent => :destroy
    accepts_nested_attributes_for :answers, :allow_destroy => true
end

答案.rb

class Answer < ActiveRecord::Base
    belongs_to :question
end

回答迁移

class CreateAnswers < ActiveRecord::Migration
  def change
    create_table :answers do |t|
      t.string :text
      t.integer :question_id
      t.boolean :correct?

      t.timestamps
    end
  end
end

在表单中,当编辑或创建新问题时 - 用户最多可以输入 4 个可能的答案,并为“正确”答案标记一个复选框。

/views/questions/_form.html.erb

<%= form_for(@question) do |f| %>
  <div class="field">
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </div>

  <p>Enter up to 4 posisble answer choices.</p>
  <%= f.fields_for :answers do |answer| %>
    <div class="field">
      <%= answer.text_field :text %>
      <%= answer.check_box :correct? %>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

来自 questions_controller.rb 的相关片段

def new
    @question = Question.new
    4.times { @question.answers.build }
  end

private
    # Use callbacks to share common setup or constraints between actions.
    def set_question
      @question = Question.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def question_params
      params.require(:question).permit(:text, :quiz_id, answers_attributes: [:id, :text, :correct?])
    end

最后 - 关于我的问题

上面列出的所有内容都运行良好,直到我添加了answer.correct?. 当我按原样提交表单时,我在日志中收到此消息:

Unpermitted parameters: correct
Unpermitted parameters: correct
Unpermitted parameters: correct
Unpermitted parameters: correct

奇怪...该参数的末尾肯定有一个问号。允许它在没有问号的情况下通过编辑控制器中允许的参数会给我这个错误消息:

unknown attribute: correct(这实际上引发了一条错误消息,我不必去挖掘日志来找到它。)

如何让表单助手阅读问号?

4

1 回答 1

1

? is not a valid character for inclusion within a column name. First, create a new database migration:

# from command line
rails generate migration ChangeCorrectInAnswers

Rename your column from correct? to correct:

# in the resulting migration
class ChangeCorrectInAnswers < ActiveRecord::Migration
  def up
    rename_column :answers, :correct?, :correct
  end
end

Run the migration:

# from command line
rake db:migrate

Finally, remove the ? from your field in the view:

# app/views/questions/_form.html.erb
<%= answer.check_box :correct %>
于 2013-08-29T00:37:13.617 回答