如何使虚拟属性成为布尔字段

Jry*_*ryl 4 ruby ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我正在尝试获取一个布尔值的虚拟属性.在这个例子中,让我们调用虚拟布尔字段children:

车型/ parent.rb

Parent
 attr_accessible :children
 attr_accessor :children
 validates_inclusion_of :children, :in => [true, false]

 def self.children=(boolean)
 end

end
Run Code Online (Sandbox Code Playgroud)

父母/ new.html.erb

<%= form_for @parent do |f| %>
  <%= f.check_box :children %>
  <%= f.submit "Create" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试使用它时,(创建一个父)它给了我错误

Children is not included in the list
Run Code Online (Sandbox Code Playgroud)

当验证出现时.

我怎么写这个?

sev*_*rin 8

你从浏览器得到的参数是一个字符串(基于你对另一个答案的评论:«而不是真和假虽然它使用0和1."parent"=> {"children"=>"1"}») .您的验证检查它是否是布尔值.

我建议以下解决方案:

首先,删除你的def self.children=()方法,它在你当前的实现中什么都不做(它是一个类方法,从不调用).

然后,实现一个自定义访问器,将String参数转换为布尔值:

class Parent
  attr_reader :children

  def children=(string_value)
    @children = (string_value == '1')
  end

  validates_inclusion_of :children, :in => [true, false]
end
Run Code Online (Sandbox Code Playgroud)

有了它,您的原始验证应该工作得很好.


shi*_*ime 6

Rails 5现在已经attribute为此添加了方法。

class Parent
  attribute :children, :boolean
end
Run Code Online (Sandbox Code Playgroud)

它正式称为“属性API”,您可以在此处找到文档:https : //api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html