I'm having this problem, I tried a lot of differents aproachs but everytime it falls in that error.
Enviroment:
Rails 3.0.5
Mongoid 2.0.1
class User
include Mongoid::Docum开发者_高级运维ent
field :name
has_and_belongs_to_many :companies
end
class Company
include Mongoid::Document
field :name
has_and_belongs_to_many :users
end
In my UserController method Create a I do something like 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 the user dont exist works great.
But if the user is already in the DB, fall a error.
NoMethodError in UserController#create
undefined method `companies' for #<Array:0x10679f638>
But after all it pushes the object into the document.
I don't know if I'm missing something.
If someone know how to solve this ... will be great.
Thanks in advance.
Try this:
@user = User.where(:email => params[:user][:email]).first
On a side note, you may also want to push some of this code into one of your models, either the User or Company model, so that in your controller you would only have one call such as:
@company.add_user(@user)
The implementation details of adding a user would then be encapsulated in your model.
You may also want to consider embedding the two calls to ActiveRecord::Base#save into a single transaction to avoid ending up with inconsistent data in your database.
精彩评论