Rails Form Helper不读取对象属性的问号

时间:2013-08-28 22:54:49

标签: ruby-on-rails

Ruby版本:2.0

Rails版本:4.0

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

question.rb

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

answer.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(这个实际上会抛出一条错误信息,我不必去挖掘日志来找到它。)

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

1 个答案:

答案 0 :(得分:1)

?不是包含在列名称中的有效字符。首先,创建一个新的数据库迁移:

# from command line
rails generate migration ChangeCorrectInAnswers

将您的专栏从correct?重命名为correct

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

运行迁移:

# from command line
rake db:migrate

最后,从视图中的字段中删除?

# app/views/questions/_form.html.erb
<%= answer.check_box :correct %>