Rails activerecord 元搜索未定义方法
我是 Rails 新手,需要您的帮助来解决一个简单的问题。
当我运行此代码时:
@search = User.search(params[:search])
@foundusers = @search.all.paginate :page => params[:page], :per_page => 20
@user = @search.where("users.id = ?", params[:id])
if @user.nil?
@user = @foundusers.first
end
unless @user.company_id.nil?
@company = Company.find(@user.company_id)
end
我收到以下错误语句: undefined method `company_id' for #
我不明白,因为数据库上的查询是正确的 (SELECT users.* FROM users LEFT OUTER JOIN Companies ON Companies.id = users.company_id WHERE (((users.firstname LIKE '%s%' OR users.lastname LIKE '%s%') OR Companies.name LIKE '%s%')) AND (users.id = '11'))
并且该用户的 company_id 不为空。
当我输入 put @user.name 时,它没有给我用户名,而是给我“用户”
非常感谢您的帮助。
I'm new to rails and need your help for what should be a simple problem.
when I run this code:
@search = User.search(params[:search])
@foundusers = @search.all.paginate :page => params[:page], :per_page => 20
@user = @search.where("users.id = ?", params[:id])
if @user.nil?
@user = @foundusers.first
end
unless @user.company_id.nil?
@company = Company.find(@user.company_id)
end
I get following error statement: undefined method `company_id' for #
I dont understand because the query on the database is correct (SELECT users.* FROM users LEFT OUTER JOIN companies ON companies.id = users.company_id WHERE (((users.firstname LIKE '%s%' OR users.lastname LIKE '%s%') OR companies.name LIKE '%s%')) AND (users.id = '11'))
and the company_id for this user is not empty.
When I type puts @user.name, instead of giving me the user name, it gives me 'User'
Many thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然您的数据库“users”表有一个名为“company_id”的列,但User模型有一个名为“company”的属性。
尝试
除非@user.company_id.nil?
@company = Company.find(@user.company.id)
结尾
Although your database 'users' table has a column called 'company_id' the User model has a property just called 'company'.
Try
unless @user.company_id.nil?
@company = Company.find(@user.company.id)
end
感谢您的帮助。实际上,我通过将模型名称@user更改为@myuser来解决这个问题。我没有改变任何其他东西并且它有效。我的猜测是该问题是由于 Devise 插件造成的,但这只是猜测......
干杯。
thanks for your help. Actually, I solved the issue by changing the model name @user into @myuser. I didn't change anything else and it works. My guess is that the issue is due to the Devise plug-in but it's just a guess...
Cheers.