Search code examples
rubyjoinormsequel

Can I execute a join from a sequel Model?


I'm using the Sequel library for a personal project, and I'm in trouble with joins specifically. I need to retrieve the complete address of a customer, that is composed of city + neighborhood. The address is broken between two tables/models, Neighborhood and City.

Basically, I have the following models:

  • Customer
  • City
  • Neighborhood

My Customer model is like so:

class Customer < Sequel::Model
  many_to_one :city
  many_to_one :neighborhood

  def complete_address
    city = join(:city).select(:city__name)
    neighborhood = join(:neighborhood).select(:neighborhood__name)

    "#{city} - #{neighborhood}"
  end
end

class City
  one_to_many :customers
end

class Neighborhood
  one_to_many :customers
end

The relations are working properly when joining like Customer.join(:city) and Customer.join(:neighborhood). But the same joins aren't working into my model.

What am I doing wrong?


Solution

  • Since you've already defined your associations (one_to_many, many_to_one) you can refer to them by name.

    For example in your Customer class, you can get at the city and neighborhood as:

    def complete_address
      "#{city.name} - #{neighborhood.name}"
    end
    

    Sequel creates references based on your relation names, and you can refer to fields within these _to_one associations with dot notation.

    https://github.com/jeremyevans/sequel/blob/master/doc/association_basics.rdoc#methods-added