当我使用 mongoid 将对象推送到文档时出现 NoMethodError
我遇到了这个问题,我尝试了很多不同的方法,但是 每次它都会犯这个错误。
环境:
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
在我的 UserController 方法中创建一个我做了这样的事情:
@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
当用户不存在时效果很好。
但如果用户已经在数据库中,则会出现错误。
NoMethodError in UserController#create
undefined method `companies' for #<Array:0x10679f638>
但毕竟它将对象推入文档中。
我不知道我是否遗漏了一些东西。
如果有人知道如何解决这个问题......那就太好了。
提前致谢。
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::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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
顺便说一句,您可能还想将其中一些代码推送到您的模型之一(用户或公司模型)中,以便在您的控制器中只有一个调用,例如
:然后,用户将被封装在您的模型中。
您可能还需要考虑将对 ActiveRecord::Base#save 的两个调用嵌入到单个事务中,以避免数据库中的数据不一致。
Try this:
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:
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.