Home Select different table fields
Reply: 3

Select different table fields

denispolicarpocampos
1#
denispolicarpocampos Published in 2018-02-08 00:20:29Z

I use rails 4 and mysql. I have two Recipe and Category models.

class Category < ApplicationRecord
  has_many :recipes
  validates_uniqueness_of :name, message: "deve ser único"
  validates_presence_of :name, message: "can't be blank"
end

class Recipe < ApplicationRecord
  belongs_to :category
end

The Recipe fields are: id, title, resume, and category_id which is the reference for category.

Category fields are: id and name

I'm trying to make a query that through the Recipe table I get as a result all the fields of the two tables. I am trying to do this with the following query:

Recipe.joins("INNER JOIN categories ON categories.id = recipes.category_id").includes("category")

But the result gives me results only from the Recipe table. The result is:

Recipe id: 1, title: "ababa", resume: nil, created_at: "2018-02-07 23:16:19", updated_at: "2018-02-07 23:16:19", category_id: 9

How can I make all the data in the two tables appear?

Pablo
2#
Pablo Reply to 2018-02-08 01:38:17Z

You can use

recipes = Recipe.includes(:category) # Get all recipes and their categories
recipe = Recipe.includes(:category).find_by(id: 1) # Get one recipe with id = 1

The includes is not mandatory, but makes an eager loading.

Then you can handle one or many recipes. For a specific recipe you can get the category.

catname = recipe.category.name # Name of the category of one recipe

catnames = [] # Empty array
recipes.each do |r|
  catnames << r.category.name # Add name of category to array of names
end

Note: The answer by Subash was almost ok, but the first statement returns an array of recipes (where returns many objects), and not a unique recipe. That's why you cannot get the category.

Subash
3#
Subash Reply to 2018-02-08 01:09:40Z

You can use includes to preload associations data, so you can do

recipe = Recipe.includes(:category).where....
category = recipe.category
Phan Việt
4#
Phan Việt Reply to 2018-02-08 01:38:12Z

Correct a bit from Subash

recipes = Recipe.includes(:category).where ...
recipes.each do |recipe|
  # category you need is here
  category = recipe.category
end
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.352533 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO