How to make a virtual attribute a logical field

I am trying to get my virtual attribute, which is logical to work with. In this example, you can call the virtual logical 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 an error

 Children is not included in the list 

when checking is done.

How do I write this?

+4
source share
4 answers

The parameter you get from the browser is a string (based on your comment on another answer: "Instead of true and false, although it uses 0 and 1." parent "=> {" children "=>" 1 "}") . Your check checks if it is logical.

I suggest the following solution:

First, delete your def self.children=() method, it does nothing in your current implementation (this is a class method and is never called).

Then we implement a custom accessory that converts the String parameter to a logical one:

 class Parent attr_reader :children def children=(string_value) @children = (string_value == '1') end validates_inclusion_of :children, :in => [true, false] end 

In doing so, your original check should work fine.

+7
source

Is it possible that params [: children] is a string? and he expected a logical one.

+1
source

There is no need to manually define the "setter" method for children, because that is exactly what attr_accessor does automatically. Try deleting your def method self.children = (boolean).

+1
source

Rails 5 has now added an attribute method for this.

 class Parent attribute :children, :boolean end 

It is officially called "API Attributes" and you can find the documentation here: https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html

0
source

All Articles