使用单选按钮时出现“validates_inclusion_of”问题

发布于 2024-11-18 09:02:11 字数 1475 浏览 2 评论 0原文

我正在使用 Ruby on Rails 3.0.7,并且在使用 validates_inclusion_of 方法时遇到问题。

我的模型文件有:

class User <  ActiveRecord::Base
  INCLUSION_VALUES = ['beautiful', 'ugly', 'good', 'bad']

  validates :test,
    :inclusion => { 
      :in => User::INCLUSION_VALUES
    }
end

在我的视图文件中,

<%= form_for(@user) do |f| %>
  <% User::INCLUSION_VALUES.each do |test| %>
    <%= f.radio_button :test, test %>
  <% end %>
<% end %>

上面的“视图”代码生成了以下内容:

<input type="radio" value="beautiful" name="user[test]" id="user_test_beautiful">
<input type="radio" value="ugly" name="user[test]" id="user_test_ugly">
<input type="radio" value="good" name="user[test]" id="user_test_good">
<input type="radio" value="bad" name="user[test]" id="user_test_bad">

无论我做什么提交表单,都会出现验证错误:

Test is not included in the list

如何解决问题?


我还尝试使用(如页面上方注释中此处所述)

%w(beautiful, ugly, good, bad)

validates_inclusion_of 格式

validates_inclusion_of :test, :in => User::INCLUSION_VALUES

  validates :test, :inclusion => User::INCLUSION_VALUES

但我总是收到验证错误。

I am using Ruby on Rails 3.0.7 and I have a problem on using the validates_inclusion_of method.

I my model file I have:

class User <  ActiveRecord::Base
  INCLUSION_VALUES = ['beautiful', 'ugly', 'good', 'bad']

  validates :test,
    :inclusion => { 
      :in => User::INCLUSION_VALUES
    }
end

In my view file I have

<%= form_for(@user) do |f| %>
  <% User::INCLUSION_VALUES.each do |test| %>
    <%= f.radio_button :test, test %>
  <% end %>
<% end %>

The above "view" code generate this:

<input type="radio" value="beautiful" name="user[test]" id="user_test_beautiful">
<input type="radio" value="ugly" name="user[test]" id="user_test_ugly">
<input type="radio" value="good" name="user[test]" id="user_test_good">
<input type="radio" value="bad" name="user[test]" id="user_test_bad">

Whatever I do submitting the form that gives me the validation error:

Test is not included in the list

How can I solve the issue?


I also tryed to use (as described here in a note above the page)

%w(beautiful, ugly, good, bad)

and the validates_inclusion_of format

validates_inclusion_of :test, :in => User::INCLUSION_VALUES

or

  validates :test, :inclusion => User::INCLUSION_VALUES

but I get always the validation error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想挽留 2024-11-25 09:02:11

解决方案(dho!)

我忘记将属性设为attr_accessible

SOLUTION (dho!)

I forget to make the attribute attr_accessible!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文