如何将 collection_select 用于具有关联的 table
How to use collection_select for a table with association
我有以下设置:
Table.rb
has_many: orders
Order.rb
belongs_to: table
order
table 的 boolean
值为 finished
我有这个脚本:
collection_select(:order, :table_id, Table.all, :id, :table, prompt: false)
我只需要select那些有订单的table就可以了。所以
if all orders for this table have order.finished == true OR if it doesn't have any orders at all { list that table }
我该怎么做?
您需要在 table.rb 中创建一个方法,其中 returns 那些有订单并已完成的表或那些没有订单的表。
def self.table_with_finished_or_no_orders
Table.joins("left join orders on orders.table_id=tables.id).where("orders.finished = ? OR orders.table_id is NULL", true)
end
您将在这样的视图中调用此方法
collection_select(:order, :table_id, Table.table_with_finished_or_no_orders, :id, :table, prompt: false)
我想我的查询是根据您的要求。
我有以下设置:
Table.rb
has_many: orders
Order.rb
belongs_to: table
order
table 的 boolean
值为 finished
我有这个脚本:
collection_select(:order, :table_id, Table.all, :id, :table, prompt: false)
我只需要select那些有订单的table就可以了。所以
if all orders for this table have order.finished == true OR if it doesn't have any orders at all { list that table }
我该怎么做?
您需要在 table.rb 中创建一个方法,其中 returns 那些有订单并已完成的表或那些没有订单的表。
def self.table_with_finished_or_no_orders
Table.joins("left join orders on orders.table_id=tables.id).where("orders.finished = ? OR orders.table_id is NULL", true)
end
您将在这样的视图中调用此方法
collection_select(:order, :table_id, Table.table_with_finished_or_no_orders, :id, :table, prompt: false)
我想我的查询是根据您的要求。