Activerecord << operator

Hello,

I am new here and actually I am writing my first RoR app.

My question is:


class Topic < ActiveRecord::Base
has_many :messages
end

class Message < ActiveRecord::Base
belongs_to :topic
end

class ForumController < ApplicationController
def post
message = Message.new(params[:message])
@topic = Topic.find(params[:id])
@topic.messages << message
end
end

Okay, this works. However, if i write

    message = Message.new(params[:message])
    @topic = Topic.find(params[:id])
    @topic.messages << message
    @topic.messages << message

(last line repeated once), then I got an primary key constraint error
message.

I understand the database message. I thought this will help:

    @topic.messages << message.dup
    @topic.messages << message.dup

but it didn’t.

I checked that the class of @topic.messages is Array, and I didn’t find
any description for the << operator in the rails manual. Does it some
special, different from Ruby? When is this arra saved (or the new
element inserted) to the database? How can I append more then one
element to the end of this ActiveRecord array?

   Mage

Operator << is the standard Ruby append/push operation

Well, I found that when I write:

active_record.subitems << subitem

the new subitem will be inserted to the database immediately. Somewhere
must be a method which does this. But where?

   Mage

take a look at the has_many documentation:

http://rails.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000471

also see the section titled “Unsaved objects and associations”
subheading
“Collections” toward the top of the page for additional information.