Forum: Ruby on Rails activerecord << operator

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D7f35c4eeff902adf48cfb4c46d6655b?d=identicon&s=25 Mage (Guest)
on 2006-02-13 19:01
(Received via mailing list)
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
946696209f50381fc280e4c0a85cceb8?d=identicon&s=25 Zachary Zolton (Guest)
on 2006-02-13 19:08
(Received via mailing list)
Operator << is the standard Ruby append/push operation
D7f35c4eeff902adf48cfb4c46d6655b?d=identicon&s=25 Mage (Guest)
on 2006-02-13 19:12
(Received via mailing list)
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
A2c85dc5ee81b12e3cc0a6522e8d079d?d=identicon&s=25 Chris Hall (Guest)
on 2006-02-13 19:26
(Received via mailing list)
take a look at the has_many documentation:

http://rails.rubyonrails.com/classes/ActiveRecord/...

also see the section titled "Unsaved objects and associations"
subheading
"Collections" toward the top of the page for additional information.
This topic is locked and can not be replied to.