Priyadarshani mini Priyadarshani mini - 1 year ago 71
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.


Answer Source

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download