1

I want to know if there is any array method to check existence of particular column in model. I have combined query results from two tables into an array. I need to check exitence of those tables column name inj that array.

2

4 Answers 4

3
Model.columns.map(&:name).include?("id")
# => true
Model.columns.map(&:name).include?("not_available_column")
# => false
Sign up to request clarification or add additional context in comments.

Comments

1

Another, perhaps cleaner way of doing this is: Foo.column_names.include?("bar")

Comments

0

This is how you can check if a model instance is of a particular class, eg obj.is_a?(Person).

To see which columns a certain model has, you do it at class level: obj.class.columns.collect { |c| c.name }.

1 Comment

even shorter: obj.class.columns.map(&:name)
0

You could use this also:

ActiveRecord::Base.connection.column_exists?(:users, :id)

Api Dock - column_exists?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.