简体   繁体   中英

Fetch data from a model and table in rails

I have a model and a table in the database (MySQL). There is a common column in both the tables. I am writing a database query using

ActiveRecord::Base.connection.execute sql
  where 
    sql = "select table_1.common_column, table_1.column_1, table_1.column_2, table_2.column_1, table_2.column_1"

This gives a result as an array of arrays with 5 columns in each array.

So, I have 2 questions

  1. Will all the array have data in the same sequence like [common_column, table_1.column_1, table_1.column_2, table_2.column_1, table_2.column_1] ?

  2. Is there any effective way that I can use?

You can join two tables by common_column and use select to indetify table columns. In my example I've questions and jobs table with common column user_id

ActiveRecord::Base.connection.select_all(
  Question.
    joins('INNER JOIN answers ON questions.asker_id = answers.answerer_id').
    select('questions.*, answers.*'))

In select you can be more detailed and alias column

select('questions.description as q_desc, answers.description as ans_desc')

Another options is to use includes , preload , eager_load methods. Here is nice article about it .

Example of usage:

Question.includes(:answers).find_each do |question|
  do_something_with_question_columns(question.column_1, question.column_2, ...)
  question.answers.each do |answer|
     do_something_with_answer_columns(answer.column_2, answer.column_2, ...)
  end
end

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