0

I am trying to create an array of ids so that I can query if a certain id is associated with an object. Here is my method but it isnt adding id's to the array.

class Report
  include Mongoid::Document

  has_and_belongs_to_many :reportapprovals, class_name: "Reportapproval", inverse_of: :report

  def bind_reportapproval
    @reportapprovals = Reportapproval.where(tenant_id: self.tenant_id).all

    if @reportapprovals.present? && @reportapprovals.any? { |ra| ra.tenant_approved == true }
      @reportapprovals.each do |ra|
        self.reportapproval_ids = ra.id
      end
    end
  end
end

This is suppose to add an array of reportapproval_ids to the report object.

4
  • Well, you set the value to each id then continually overwrite it. Commented Aug 14, 2015 at 0:52
  • ok, how do i fix that add them to an array with <<? Also when I look at it in console there are NO id's? Commented Aug 14, 2015 at 0:53
  • 1
    In the if statement you've got this: @reportapprovals.any? { |tenant_approved| tenant_approved == true} which is going to iterate through each reportapproval and check if it is equal to true, but it won't ever be since it will be an instance of a Mongoid record. Did you maybe mean something like this? @reportapprovals.any? { |ra| ra.tenant_approved == true} Commented Aug 14, 2015 at 0:54
  • thanks for that @neuronaut! Commented Aug 14, 2015 at 1:05

2 Answers 2

1

Rails actually has a method for that:

if @reportapprovals.present? && @reportapprovals.any? { |tenant_approved| tenant_approved }
  self.reportapproval_ids = @reportapprovals.ids
end
Sign up to request clarification or add additional context in comments.

Comments

1

You're setting the value of the array equal to ONE ID. Try this:

if true # use correct conditional statement
  self.reportapproval_ids = @reportapprovals.pluck(:id)
end

1 Comment

Thanks I appreciate the answer but the other is cleaner.

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.