当我尝试提交表单时,为什么会收到“未包含在列表中”的错误消息?

我正在使用事件记录中的包含验证助手:

SUBJECTS = ['foo','bar']
validates :subject, inclusion: %w(SUBJECTS)

在我看来,选择列表按预期显示:

使用表单助手生成的选择标记是:
<select class="form-control" id="message_subject" name="message[subject]">
  <option selected="selected" value="foo">foo</option>
  <option value="bar">bar</option>
</select>

看法:
<div class="row top25">
  <%= form_for @message, url: {action: "create"}, html: {role: "form"} do |form| %>
  <fieldset class="fields">
    <div class="form-group">
      <%= form.label :name %><%= @message.errors[:name].join(", ") %>
      <%= form.text_field :name, class: "form-control"%>
    </div>

    <div class="form-group">
      <%= form.label :email %><%= @message.errors[:email].join(", ") %>
      <%= form.text_field :email, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= form.label :subject %><%= @message.errors[:subject].join(", ") %>
      <%= form.select(:subject, Message::SUBJECTS,{}, class: "form-control") %>
    </div>

    <div class="form-group">
      <%= form.label :body %><%= @message.errors[:body].join(", ") %>
      <%= form.text_area :body, class: "form-control", rows: "10" %>
    </div>
  </fieldset>

  <fieldset class="actions">
    <%= form.submit "Send" %>
  </fieldset>
  <% end %>
</div>

消息模型:
class Message

  SUBJECTS = ['foo','bar']

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :subject, :body

  validates :name, :email, :subject, :body, :presence => true
  validates :subject, inclusion: %w(SUBJECTS)
  validates :email, :format => { :with => %r{.+@.+\..+} }, :allow_blank => true

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

end

最佳答案

您没有正确创建数组。当您调用 %w() 时,您是在告诉 ruby​​ 参数将被视为字符串,而不是变量。查看我添加的返回值。

SUBJECTS = ['foo','bar'] #=> ["foo", "bar"]
validates :subject, inclusion: %w(SUBJECTS) #=> ["SUBJECTS"]

你想要做的是:
SUBJECTS = ['foo','bar']
validates :subject, inclusion: SUBJECTS

或这个:
validates :subject, inclusion: %w(foo bar)

关于ruby-on-rails - 为什么我收到错误 "is not included in the list"? ( rails 4),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21171092/

10-13 04:49