Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Ruby - How to check if an attr_accessor field exists?

In Rails 3/4 model, if a field field1 is declared with attr_accessor:

attr_accessor :field1

How to check late on if field1 exists in the model?. column_exists? and method_defined? seem only working with model column and field1 is not a model column.

like image 777
user938363 Avatar asked Apr 14 '15 04:04

user938363


2 Answers

attr_accessor defines two methods: def field1 and def field1=(val), so the best you can do is check for existence of these two functions.

If you have an object:

object.respond_to? :field1
object.respond_to? :field1=

If you don't, use:

Class.instance_methods.include? :field1
Class.instance_methods.include? :field1=
like image 197
makhan Avatar answered Sep 28 '22 03:09

makhan


attr_accessor will create getter and setter method in class

In Rails, the method column_names will return the array of column names. You can check if the column is present in it or not.

ModelClass.column_names.include?('column_name')

If you are not using Rails but just plain old Ruby and you want to check if getter setter are defined then you should use respond_to? method on the object.

like image 27
Hardik Avatar answered Sep 28 '22 02:09

Hardik