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?
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.
Concerning 1. & 2., I summarized the different meanings of <<
here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With