Search code examples
ruby-on-railsrubyruby-on-rails-7

querying another model in a rails model function


Basically, what I'm trying to do is a join on a text field rather than an id like

SELECT country.delivery_time 
FROM order, country
WHERE order.country = country.name

and what I've got so far for my Rails models is

class Country < ApplicationRecord
  validates :name, presence: true
  validates :delivery_time, presence: true
end

class Order < ApplicationRecord
  validates :country, presence: true

  def shipping_time
    # want to get the correct country from the DB
    if self.country == country.name
      country.delivery_time
    else
      "unavailable"
    end
  end
end

where shipping_time is the function that should return the result of the join. The error I'm getting is

undefined method `country'

I'm using Ruby 3.0.3 and Rails 7.0.0.


Solution

  • So I ended up using the joins function to get what I wanted,

    Order.joins("INNER JOIN countries ON orders.country = countries.name")
    

    where the full function is

    def shipping_time
      relation = Order.joins("INNER JOIN countries ON orders.country = countries.name")
      if 1 == relation.count()
        relation[0].delivery_time
      else
        "unavailable"
      end
    end