glarkou
glarkou

Reputation: 7101

Comparing models Ruby on Rails

I have one model call Permissions of about 60 columns where half of the column represents a boolean and half of them a text (:string) field.

I would like to be able to compare 2 different objects of this model.

The comparison will be able to present ONLY the True values of the 1st Object compared with the equivalent columns in the other object. Forget about the values containing or not text!

For example:

Object 1:

Permission:
    Read_disk :true
    Write_disk :true
    Modify_disk :true
    Delete_disk :true
    Every other permission FALSE or TEXT so I do not care about them. 

Object 2:

Permission:
    Read_disk :false     (*I care about that because it was true in object 1)
    Write_disk :false    (*I care about that because it was true in object 1)
    Modify_disk :true    (*I care about that because it was true in object 1)
    Delete_disk :true    (*I care about that because it was true in object 1)
    Every other might be TRUE or FALSE or TEXT but I do not care about them because those permissions were false in the object 1

In my view I would like to present this comparison showing only the true columns of Object 1 and the equivalent fields of Object 2

Any suggestions?

Thanks.

Upvotes: 0

Views: 2157

Answers (2)

gunn
gunn

Reputation: 9165

class Permissions < ActiveRecord::Base
  def compare(permission)
    true_attributes = self.attributes.select{|k, v| v==true }
    equivalent_attributes = permission.attributes.select{|k, v| true_attributes.key?(k) }

    [true_attributes, equivalent_attributes]
  end
end

object_1_permissions, object_2_permissions = object_1.compare(object_2)

Upvotes: 1

vinceh
vinceh

Reputation: 3510

If I understand your question correctly, you want to be able to find records of your Object in relation to another record. This isn't too hard

obj = Object.find(some_id)
conditions = Hash.new
obj.attributes.each do |key, value|
    if value == true
        conditions[key] = value
    end
end
interestingObjects = Object.where(conditions).all

And then your interestingObjects will have the records you want!

Upvotes: 1

Related Questions