Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting the error "is not included in the list"? (Rails 4)

Why am I getting the error "is not included in the list" when I attempt to submit the form?

I am using the inclusion validation helper from active record:

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

In my view the select list appears as expected: enter image description here

The select markup produced using the form helper is:

<select class="form-control" id="message_subject" name="message[subject]">
  <option selected="selected" value="foo">foo</option>
  <option value="bar">bar</option>
</select>

View:

<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>

Message model:

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
like image 528
Sheldon Avatar asked Mar 21 '23 22:03

Sheldon


1 Answers

You are not creating your array correctly. When you call %w(), you are telling ruby that the parameters are to be treated as strings, not variables. Check out the return values that I've added.

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

What you want to do is this:

SUBJECTS = ['foo','bar']
validates :subject, inclusion: SUBJECTS

Or this:

validates :subject, inclusion: %w(foo bar)
like image 78
Josh Avatar answered Mar 23 '23 11:03

Josh