Priyadarshani mini Priyadarshani mini - 19 days ago 5
MySQL Question

Sorting by another related model attributes - Ruby on Rails

I have two models related with each other as below

class Weed < ApplicationRecord
has_many :user_transactions,:dependent => :destroy
end


This weed model has an attribute name county

and related model:

class UserTransaction < ApplicationRecord
belongs_to :weed
end


Now I want to fetch records from UserTransaction model on the basis of sort by county in weed model and find by county too.

Please suggest me, How can I get correct result with in minimum complexity.

Thanks.

Answer

If you want to sort by county you can do like this:

UserTransaction.joins(:weed).order("weeds.county DESC")

or if you want to find by county then use :

UserTransaction.joins(:weed).where("weeds.county"=> "xyz")
Comments