Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a virtual attribute be a boolean field

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?

like image 273
Jryl Avatar asked Aug 07 '12 23:08

Jryl


2 Answers

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

like image 181
shime Avatar answered Oct 24 '22 22:10

shime


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.

like image 28
severin Avatar answered Oct 24 '22 23:10

severin