I know that similar questions were published in the past, and I tried to find a solution in the rails manuals or in the answers to previous posts, but either the answers did not work for me, or they were not what I was looking for. I have previous SQL experience (mainly MySQL) and I'm currently learning Rails for a new project.
I have a user table and a company table. A user always belongs to only one company, but a company can have many users. simple view of my data:
users has the following attributes: id (INT), name(string), email(string), company_id
companies has the following attributes: id (INT), company_name(string), address(string)
When I execute the following SQL query directly in the database (not in rails):
SELECT users.name, company.address FROM companies INNER JOIN users on
users.company_id=companies.id
I get a response to 2 columns named users.name in the first and company.adres to which this user refers in the second column. Since this is an internal union, companies without users or users without companies are not listed, which is exactly what I need.
Now, trying to "translate" this request into rails (I use Rails 4.1.1), I first defined the User model and the company model by creating the corresponding user.rb and company.rb in the model directory. For user.rb, I declared "belongs_from: company" and for company .rb I declared "has_many: users".
After migration, etc. I use the rails console to add some data and test. All requests for individual models work fine, as well as requests such as
Users.find(1).company.address
works fine, but when I print the following command:
e = Company.select("companies.company_name, users.name").joins(:users)
, SQL :
SELECT companies.company_name, users.name FROM "companies" INNER JOIN "users" ON "users"."company_id" = "companies"."id"
, , , , . , users.name . (.. ), , user.name:
#<ActiveRecord::Relation [#<Company id: nil, address: "addresexample1">, #<Company id: nil, address: "addresexample3">, #<Company id: nil, address: "addressexample4">]>
- -, Rails?