Flip
Flip

Reputation: 6781

What is the Ruby equivalent for Rails' "has_one" method?

I am writing a Ruby application. In there I have two classes, that have a 1:1 relation. In Rails I would use ActiveRecord's has_one method on each function. But in Ruby, and without a database, I am not sure what to do.

How do I define relations / associations between classes in Ruby?

Edit: This is not about a specific problem I have at the moment. I just wondered how I would express Rails has_one (respectively has_many, belongs_to) in pure Ruby code. The two classes I mentioned above are: 1. A class that runs a search algorithm. 2. A class that I use to handle user input that I need during the search process and that also displays results of intermediate steps and statistics.

Maybe what I am asking for doesn't make sense as it can be expressed without a dedicated method like has_one? Or because it is never needed without a DB?

Upvotes: 0

Views: 87

Answers (1)

Jesper
Jesper

Reputation: 4555

You can define relations as attributes like this:

class Foo
  attr_accessor :one, :many
  def initialize
    @many = []
  end
end

class Bar
end

foo = Foo.new
bar = Bar.new
other_bar = Bar.new
foo.one = bar
foo.many << other_bar
foo.many << bar

p foo.one
# => #<Bar:0x21d5c1a0>
puts foo.many
# => [#<Bar:0x538613b3>, #<Bar:0x21d5c1a0>]

Upvotes: 5

Related Questions