How to combine 2 Rails models in one place?

I have two models that are not related (in the sense of db), but have some common columns (Name, Email, etc.).

Class Account < ActiveRecord::Base

end


Class LegacyAccount < ActiveRecord::Base

end

For various reasons, I cannot combine them into one model or make an STI. But I would like for a simple view to display all the records of both models in a good table (possibly sorted by a common field of type "name").

Can I search / query from both models? Or can I make two finds and combine the resulting arrays so that they are sorted? Can I use some intermediate model to combine both?

+3
source share
4 answers

, , Ruby, .

class AccountView
  def self.find_all
    accounts = []
    Account.find(:all).each do |account|
      accounts << {:name => account.name, ... }
    end
    LegacyAccount.find(:all).each do |account|
      accounts << {:name => account.name, ... }
    end
    return accounts
  end
end

, AccountView AccountView.

+1

- , Array:

@accounts = (LegacyAccount.all + Account.all).sort{|x,y| x.name <=> y.name}

, Account, , Account.find_all - .


SQL:

@accounts = Account.find_by_sql("SELECT * FROM accounts UNION SELECT * FROM legacy_accounts")

SQL, Rails. , LegacyAccounts, . , , LegacyAccounts , .

- : http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html

2 , , - .

+6

Only my 2 cents here is what I used for the site’s RSS feed:

(Model1.latest + Model2.latest).sort_by(&:created_at).reverse
+1
source
@accounts = Account.find(:all, :include => :legacy_account)

or Rails3 join style

@accounts = Account.all.joins(:legacy_account)
-1
source

Source: https://habr.com/ru/post/1756016/


All Articles