Priyadarshani mini Priyadarshani mini - 3 months ago 19
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

This weed model has an attribute name county

and related model:

class UserTransaction < ApplicationRecord
belongs_to :weed

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.



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")