Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About "<<" operator in this Rails association case

I am a newbie in Ruby on Rails. In a Rails application, I saw some code like following:

In model, there is a class Car:

class Car < ActiveRecord::Base
  ...
end

In controller, there is a method "some_method"

class CarsController < ApplicationController

   def some_method
      @my_car = Car.new()

      #What does the following code do? 
      #What does "<<" mean here?
      @my_car.components << Component.new()
   end


end

I got three questions to ask:

1. In the code in controller @my_car.components << Component.new() , what does it do? What << means ?

2. Are there any other usages of "<<" in Ruby-On-Rails or in Ruby ?

3. Does Car class must explicitly define the has_many association with Component class if "<<" is used Or is the "<<" can be used to add a new association to Car, even the association is not defined in Car class explicitly?

like image 995
Mellon Avatar asked Oct 26 '11 07:10

Mellon


2 Answers

After your edit:

Point 1

@my_car.components << Component.new()

is the same as

@my_car.components.push(Component.new())

Point 2

It lets you add items to a collection or even concatenate strings.

Some links:

  • for arrays

  • for strings

  • for io streams

notice you can naturally overload or define your own.

Point 3

Relationships must be explicit, otherwise Rails can't create the adequate methods: @my_car.components wouldn't have any sense.

like image 178
apneadiving Avatar answered Sep 25 '22 14:09

apneadiving


Concerning 1. & 2., I summarized the different meanings of << here.

like image 24
emboss Avatar answered Sep 24 '22 14:09

emboss