cuốn sách gpt4 ai đã làm

ruby-on-rails - 来自 pluck 的漂亮数组

In lại Tác giả: Vũ trụ không gian 更新时间:2023-11-03 17:15:32 25 4
mua khóa gpt4 Nike

我有一个模型,我喜欢我可以使用的弹拨方法。如果我这样做:

@x = AwesomeModel.all.pluck(:column_one, :column_two)

然后我得到一个多维数组:@x[][]。凭借我可悲的技能,我使用数字与他们一起工作:

@x[0][1]

我怎样才能使用 pluck 或类似的方法来访问这样的数组:

@x[0][:column_two]

câu trả lời hay nhất

如果您担心从数据库返回的结构,您应该简单地执行以下操作:

@x = AwesomeModel.all.select(:column_one, :column_two)

那么您将保持快速数据库查询的优势 + 拥有 AwesomeModel 实例,但只有 column_onecolumn_two điền vào


或者如果您希望手动执行此操作:

@x = AwesomeModel.all.pluck(:column_one, :column_two).map do |array|
OpenStruct.new({column_one: array[0], column_two: array[1] }) }
end

然后你就可以像普通模型一样使用它了:

@x[0].column_one
# or even
@x[0][:column_two]

关于ruby-on-rails - 来自 pluck 的漂亮数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25767243/

25 4 0
không gian vũ trụ
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress