title: How to UNION tables and make results accessible in a Ruby view
body: <p>I'm quite new to RoR and creating a student project for a course I'm taking. I'm wanting to construct a type of query we didn't cover in the course and which I know I could do in a snap in .NET and SQL. I'm having a heck of a time though getting it implemented the Ruby way.</p>
  
  <p><strong>What I'd like to do:</strong> Display a list on a user's page of all "posts" by that user's friends.</p>
  
  <p>"Posts" are found in both a <code>questions</code> table and in a <code>blurbs</code> table that users contribute to. I'd like to <code>UNION</code> these two into a single recordset to sort by updated_at DESC.</p>
  
  <p>The table column names are not the same however, and this is my sticking point since other successful answers I've seen have hinged on column names being the same between the two.</p>
  
  <p>In SQL I'd write something like (emphasis on <em>like</em>):</p>
  
  <pre><code>SELECT b.Blurb AS 'UserPost', b.updated_at, u.username as 'Author'
  FROM Blurbs b
  INNER JOIN Users u ON b.User_ID = u.ID
  WHERE u.ID IN 
    (SELECT f.friend_id FROM Friendships f WHERE f.User_ID = [current user])
  ORDER BY b.updated_at DESC
  
  UNION
  
  SELECT q.Question, q.updated_at, u.username
  FROM Questions q
  INNER JOIN Users u ON q.User_ID = u.ID
  WHERE u.ID IN 
    (SELECT f.friend_id FROM Friendships f WHERE f.User_ID = [current user])
  ORDER BY b.updated_at DESC
  </code></pre>
  
  <p>The User model's (applicable) relationships are:</p>
  
  <pre><code>has_many :friendships
  has_many :friends, through: :friendships
  has_many :questions
  has_many :blurbs
  </code></pre>
  
  <p>And the Question and Blurb models both have <code>belongs_to :user</code></p>
  
  <p>In the view I'd like to display the contents of the 'UserPost' column and the 'Author'. I'm sure this is possible, I'm just too new still to ActiveRecord and how statements are formed. Happy to have some input or review any relevant links that speak to this specifically!</p>
  
  <p><strong>Final Solution</strong></p>
  
  <p>Hopefully this will assist others in the future with Ruby <code>UNION</code> questions. Thanks to @Plamena's input the final implementation ended up as:</p>
  
  <pre><code>def friend_posts
    sql = "...the UNION statement seen above..."
  
    ActiveRecord::Base.connection.select_all(ActiveRecord::Base.send("sanitize_sql_array",[sql, self.id, self.id] ) )
  end
  </code></pre>