ruby on rails - NoMethodError when I push a object into a Doc with mongoid -


i'm having problem, tried lot of differents aproachs everytime falls in error.

enviroment:

rails 3.0.5

mongoid 2.0.1

class user  include mongoid::document    field :name    has_and_belongs_to_many :companies  end   class company   include mongoid::document    field :name    has_and_belongs_to_many :users  end  

in usercontroller method create this:

@user = user.where(:email => params[:user][:email])   if @user.count > 0    @user.companies.push(@company)    @user.save    @company.users.push(@user)    @company.save   else    @user = user.create(:name => params[:user][:name],                        :email => params[:user][:email],                        :password => "123456")     @user.companies.push(@company)    @user.save    @company.users.push(@user)    @company.save   end  

when user dont exist works great.

but if user in db, fall error.

nomethoderror in usercontroller#create  undefined method `companies' #<array:0x10679f638>  

but after pushes object document.

i don't know if i'm missing something.

if know how solve ... great.

thanks in advance.

try this:

@user = user.where(:email => params[:user][:email]).first 

on side note, may want push of code 1 of models, either user or company model, in controller have 1 call such as:

@company.add_user(@user) 

the implementation details of adding user encapsulated in model.

you may want consider embedding 2 calls activerecord::base#save single transaction avoid ending inconsistent data in database.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -