Search code examples
rubyruby-on-rails-5block

How pass yield in method as param


I have method:

def return_dto_object(id)
    Comment.where(product_id: id)
end

And i wanna pass block and put it instead of product_id For Example:

def return_dto_object(id)
    Comment.where(yield: id)
end

=> return_dto_object(1) { product_id }
=> return_dto_object(1) { id }

I just wanna change the column that the records will search for. This possible, that i want?


Solution

  • where is able to receive a hash as an argument, so, whenever you do:

    Comment.where(product_id: id)
    

    It's equivalent to:

    Comment.where({ product_id: id })
    

    You can create a hash with "dynamic" keys the way:

    { key => value }
    

    So, passing product_id, it'd be:

    attribute = :product_id
    { attribute => 1 } # {:product_id=>1}
    

    Which is the valid syntax for invoking where:

    def return_dto_object(attribute, id)
      Comment.where(attribute => id)
    end
    

    If it's confusing, you can first create the hash, and pass it to where.