i have a problem with saving 2 items in db at one moment(i am using rails 3.1). I have model Message
class Message < ActiveRecord::Base
belongs_to :user
validates_presence_of :content
end
Message model have params: user_id(reciever), user_from(sender), and content(text)
and model User is
class User < ActiveRecord::Base
has_many :posts
has_many :messages
end
in MessagesController i have method
def create
@message =Message.new(params[:message])
User.find(@message.user_id).messages.build(params[:message])
User.find(@message.user_from).messages.build(params[:message])
end
and the problem is that User.find(@message.user_id) only have this message , user_from dont have. I even have tryed this User.find(2).messages.build(params[:message]) instead of User.find(@message.user_from).messages.build(params[:message]) and user with id 2 dont have this message too, only user with user_id have. what i am doing wrong??
Thanks in advance
Use
createrather thanbuild.buildis used when you want to create an model instance but don’t want to save it immediately. In your case the message instances are being created but not saved.