I'm trying to get my virtual attribute that is a boolean to work. In this example, lets call the virtual boolean field children
:
models/parent.rb
Parent
attr_accessible :children
attr_accessor :children
validates_inclusion_of :children, :in => [true, false]
def self.children=(boolean)
end
end
parents/new.html.erb
<%= form_for @parent do |f| %>
<%= f.check_box :children %>
<%= f.submit "Create" %>
<% end %>
Right now when I try to use it, (create a parent) it gives me the error
Children is not included in the list
when the validation comes up.
How do I write this?
Rails 5 has now added the attribute
method for this.
class Parent
attribute :children, :boolean
end
It's officially called "attributes API" and you can find the documentation here: https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html
The param you get from the browser is a String (based on your comment to the other answer: «Instead of true and false though its using 0 and 1."parent"=>{"children"=>"1"}»). Your validation checks whether it is a boolean.
I suggest the following solution:
First, Remove your def self.children=()
method, it does nothing at all in your current implementation (it is a class method and never called).
Then, implement a custom accessor that converts the String param into a boolean:
class Parent
attr_reader :children
def children=(string_value)
@children = (string_value == '1')
end
validates_inclusion_of :children, :in => [true, false]
end
With that your original validation should work just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With