I have the Color, House, Urbanismno and City models, where the Color model belongs to the House model, the House model belongs to the Urbanism model, and the Urbanism model belongs to the City model.
Here are the partial codes of the models involved:
Model Color
class Color < ActiveRecord::Base
belongs_to :casa
def ciudad_id
casa.urbanismo.ciudad_id
end
end
Model House
class Casa < ActiveRecord::Base
belongs_to :urbanismo
end
Urbanism Model
class Urbanismo < ActiveRecord::Base
belongs_to :ciudad
end
I want to know all the houses of a certain color in a certain city, for example I want to know the number of houses of blue color in the city with id = 1
In the controller I call a method with a parameter:
nombre_de_color = 'azul'
ciudad_id = 1
casas_de_color(nombre_de_color, ciudad_id)
In a helper I have these two proposals:
Proposal 1:
def casas_de_color(nombre_de_color, ciudad_id)
contador = 0
Color.where(nombre: nombre_de_color).each do |color|
contador += 1 if color.casa.urbanismo.ciudad_id == ciudad_id
end
contador
end
If I create the city_id attribute within the Color model, as seen above, I can do the following query, but it is practically the same as the previous one.
Proposal 2:
def casas_de_color(nombre_de_color, ciudad_id)
contador = 0
Color.where(nombre: nombre_de_color).each do |color|
contador += 1 if color.ciudad_id == ciudad_id
end
contador
end
How can I enhance these proposals in a helper using the Ruby convention?
It is not a Ruby convention problem, but to fetch all the necessary information from the DB in the same query without having to iterate over each element. First thing, it would be to add in
Casa
the relation that it has withColor
.so I think the main query should be about the model
Casa
because you want to know how many houses are of a certain color in a certain city, right?That should return your total bill.