简体   繁体   中英

Rails Single Results from Multiple Tables

Using Rails 4.2

I have two models, suppliers and clients . Both models contain a name (string) and email (string). They do not have any relationship between them.

I would like to generate a list of all the names and emails from both suppliers and clients. In this list I would also like to know if the partner is a supplier or client.

Controller

@suppliers = Supplier.all
@clients = Client.all

@all_partners = (@suppliers + @clients).sort { |x, y| x.name <=> y.name }

View

<% @all_partners.each do |partner| %>
  <%= partner.name %>, <%= partner.email %>, <%= partner.type %>
  <!-- I need some way to know if the partner type is a supplier or client -->
<% end %>

How can I put in which type of partner it is? Is there a way to do this with one single AR call or query? This is basically how to use an SQL Union statement in Rails.

您可以获得我相信的对象的类名称<%= partner.class.model_name.human %>

Thanks for the help all.

I ended up using the same controller as in the question, with some additional information in the view.

View

<% @all_partners.each do |partner| %>
  <%= partner.name %>, <%= partner.email %>, <%= partner.try(:client_type) %>, <%= partner.class.model_name.human  %>
<% end %>

Union in ActiveRecord works only within a single model. You could use union for two different tables using raw SQL, something like this:

Supplier.connection.execute("(SELECT id, ..., 'suppliers' as table FROM suppliers WHERE...) UNION (SELECT id,... 'clients' as table FROM clientsWHERE...)")

but the result would be of type PG::Result. So the best way, unfortunately, is to use two ActiveRecord queries. OR if clients and suppliers have similar fields, you could put them in one table

class Partner < ActiveRecord::Base
  default_scope where(is_supplier: true)
  scope :clients, -> { where(is_supplier: false) }
end

so Partner.all will output only suppliers, Partner.unscoped - all partners

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM