如何在方法中将 yield 作为参数传递
How pass yield in method as param
我有方法:
def return_dto_object(id)
Comment.where(product_id: id)
end
我想传递方块并放置它而不是 product_id
例如:
def return_dto_object(id)
Comment.where(yield: id)
end
=> return_dto_object(1) { product_id }
=> return_dto_object(1) { id }
我只想更改记录将搜索的列。这可能,我想要的?
where
能够接收散列作为参数,因此,无论何时:
Comment.where(product_id: id)
相当于:
Comment.where({ product_id: id })
您可以使用 "dynamic" 键创建散列,方法如下:
{ key => value }
所以,通过 product_id,它将是:
attribute = :product_id
{ attribute => 1 } # {:product_id=>1}
调用 where
:
的有效语法是什么
def return_dto_object(attribute, id)
Comment.where(attribute => id)
end
如果混淆,你可以先创建哈希,然后将它传递到 where。
我有方法:
def return_dto_object(id)
Comment.where(product_id: id)
end
我想传递方块并放置它而不是 product_id
例如:
def return_dto_object(id)
Comment.where(yield: id)
end
=> return_dto_object(1) { product_id }
=> return_dto_object(1) { id }
我只想更改记录将搜索的列。这可能,我想要的?
where
能够接收散列作为参数,因此,无论何时:
Comment.where(product_id: id)
相当于:
Comment.where({ product_id: id })
您可以使用 "dynamic" 键创建散列,方法如下:
{ key => value }
所以,通过 product_id,它将是:
attribute = :product_id
{ attribute => 1 } # {:product_id=>1}
调用 where
:
def return_dto_object(attribute, id)
Comment.where(attribute => id)
end
如果混淆,你可以先创建哈希,然后将它传递到 where。