0

I have a migration file written as such:

 class Character < ActiveRecord::Migration
   def change
     create_table :character_attributes do |t|
       t.string :character_name
       t.boolean :attr1, default: false, null: false
       t.boolean :attr2, default: false, null: false
       t.boolean :attr3, default: false, null: false
       t.boolean :attr4, default: false, null: false
       t.boolean :attr5, default: false, null: false
       t.boolean :attr6, default: false, null: false
       t.boolean :attr7, default: false, null: false     
       t.timestamps null: false
     end
   end
 end

Essentially, each character has 7 possible attributes yet can only have one (in other words, if one of the seven fields is true, the rest will be false).

Other discussions (i.e. Rails 4.x how to query boolean value with activerecord?) query from the model. But can you write the code as such so that rails queries through the multiple fields/attributes within the object? i.e.

 Character.find_by_character_name("Jack").where(:attributes => true) 

Also, I understand redesigning the schema can be an option, but for now I'd just like to know if the query can be done.

2
  • 1
    It's hard for me to understand a scenario where you would want this kind of table structure. Seems like a simple status enum column would do the trick: api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html Commented Sep 18, 2015 at 3:01
  • What Wes said. Put simply, this needs to be a single field with a value of "attr1" through "attr7", or whatever they are. Commented Sep 18, 2015 at 3:32

1 Answer 1

0

You can use OR.

def attributes(value)
  v = value ? 1 : 0
  <<-EOS
    attr1 = #{v} OR
    attr2 = #{v} OR
    attr3 = #{v} OR
    attr4 = #{v} OR
    attr5 = #{v} OR
    attr6 = #{v} OR
    attr7 = #{v}
  EOS
end

Character.find_by_character_name("Jack").where(attributes(true))

This can be made more compact, dynamic, and also moved to a class method on the model. But I think this gives you the idea.

Sign up to request clarification or add additional context in comments.

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.